Skip to main content

[SOLVED] How to create User/Database in script for Docker Postgres - docker

[SOLVED] A Simple Guide to Creating Users and Databases in Docker Postgres

In this article, we will look at different ways to create users and databases in PostgreSQL using Docker. Managing PostgreSQL databases is important for developers and admins. Using Docker helps us to make database management easier. It also helps us to set up and keep our applications running smoothly. We will talk about several solutions for different needs.

Here’s a quick look at the solutions we will discuss:

  • Solution 1 - Use Dockerfile to Create User and Database
  • Solution 2 - Start Databases with SQL Scripts
  • Solution 3 - Use Environment Variables for User and Database
  • Solution 4 - Create Users and Databases with Docker Compose
  • Solution 5 - Manage Permissions for the New User
  • Solution 6 - Check User and Database Creation

If we are new and want to learn how to create a user or database in Docker Postgres, or if we are experienced developers wanting to improve our process, this guide will give us helpful tips and easy solutions. If we want to know more about Docker, we can read this article on the difference between ports or learn about how to mount host volumes. Let’s start!

Solution 1 - Using Dockerfile to Create User and Database

We can create a user and a database in PostgreSQL using a Dockerfile. It is easy to extend the official PostgreSQL image. This way, we can set up our PostgreSQL environment with the user and database during the image build.

Step-by-Step Instructions

  1. Create a Dockerfile: First, make a file named Dockerfile in our project folder.

  2. Extend the PostgreSQL Image: We will use the official PostgreSQL image as our base image. We will add commands to create a user and a database.

  3. Add Environment Variables: We can set up the user and database using environment variables that the PostgreSQL image gives us.

Here is a sample Dockerfile:

# Use the official PostgreSQL image
FROM postgres:latest

# Set environment variables for PostgreSQL
ENV POSTGRES_USER=myuser
ENV POSTGRES_PASSWORD=mypassword
ENV POSTGRES_DB=mydatabase

# Expose the PostgreSQL port
EXPOSE 5432

Build the Docker Image

After we create our Dockerfile, we can build the Docker image. Run this command in our terminal:

docker build -t my-postgres-image .

Run the Docker Container

Once we build the image, we can run a container from this image:

docker run --name my-postgres-container -d my-postgres-image

Verify User and Database Creation

We can check if the user and database are created by connecting to the PostgreSQL container:

docker exec -it my-postgres-container psql -U myuser -d mydatabase

This command will open a PostgreSQL shell. Here, we can run SQL commands. To list all databases, we can use:

\l

Additional Information

This method makes it easy to create a user and database when we deploy PostgreSQL in Docker. For more details on Dockerfiles, we can look at the Dockerfile guide.

Using the Dockerfile way, we can make sure our PostgreSQL setup is easy to repeat and controlled by version. We can also learn more about managing PostgreSQL permissions in the next section.

Solution 2 - Initializing Databases with SQL Scripts

To set up databases in Docker PostgreSQL using SQL scripts, we can use Docker’s own way to run these scripts. When we start a PostgreSQL container, it looks in a special folder for files to run during the setup. This helps us create users, databases, and tables with SQL commands.

Step-by-Step Process

  1. Create SQL Initialization Script: First, we make a SQL file (like init.sql). This file has the SQL commands to create our user and database. Here is an example of what the file can look like:

    -- init.sql
    CREATE DATABASE mydatabase;
    CREATE USER myuser WITH ENCRYPTED PASSWORD 'mypassword';
    GRANT ALL PRIVILEGES ON DATABASE mydatabase TO myuser;
  2. Dockerfile Configuration: If we use a Dockerfile to set up our PostgreSQL container, we can copy the SQL script into the container’s setup folder. The usual folder for initialization scripts in the official PostgreSQL Docker image is /docker-entrypoint-initdb.d.

    Here is an example of a Dockerfile:

    FROM postgres:latest
    
    # Copy the initialization SQL script to the designated directory
    COPY init.sql /docker-entrypoint-initdb.d/
  3. Build the Docker Image: After we create our Dockerfile and SQL script, we can build our Docker image. We run this command in our terminal:

    docker build -t my-postgres-image .
  4. Run the Docker Container: Now we can run our PostgreSQL container using the image we just built. We use this command:

    docker run --name my-postgres-container -d my-postgres-image
  5. Accessing the PostgreSQL Database: After our container is running, we can connect to the PostgreSQL database to check if the user and database were created. We can use a PostgreSQL client or the command line:

    docker exec -it my-postgres-container psql -U myuser -d mydatabase

Important Notes

  • Any .sql files in the /docker-entrypoint-initdb.d folder will run one after another when the container starts.
  • If the database is already there, the scripts in this folder will not run again unless we remove the volume linked to the container or start with a new container.
  • For more details on working with Docker and PostgreSQL, we can check this guide on connecting to PostgreSQL in Docker.

By following these steps, we can successfully set up a PostgreSQL database in a Docker container using SQL scripts. This gives us an easy way to automate the setup of our database environment.

Solution 3 - Using Environment Variables to Set User and Database

When we use Docker to deploy a PostgreSQL database, one easy way to create a user and a database is by using environment variables. PostgreSQL Docker images know how to read certain environment variables. These help us set up the database when it starts.

To create a user and database with environment variables, we can use the following variables in our docker run command or in a docker-compose.yml file:

  • POSTGRES_USER: This variable sets the name of the superuser
  • POSTGRES_PASSWORD: This variable sets the password for the superuser
  • POSTGRES_DB: This variable creates a new database with the name we choose

Example Using docker run

Here is how we can set these environment variables in a docker run command:

docker run --name my-postgres -e POSTGRES_USER=myuser -e POSTGRES_PASSWORD=mypassword -e POSTGRES_DB=mydatabase -d postgres

In this command:

  • --name my-postgres gives the container a name we can remember
  • -e POSTGRES_USER=myuser sets the username to myuser
  • -e POSTGRES_PASSWORD=mypassword sets the password for the user
  • -e POSTGRES_DB=mydatabase creates a database called mydatabase
  • -d postgres runs the container in detached mode with the official PostgreSQL image

Example Using Docker Compose

If we use Docker Compose, we can define these environment variables in our docker-compose.yml file. Here is an example:

version: "3.8"

services:
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mypassword
      POSTGRES_DB: mydatabase
    ports:
      - "5432:5432"

In this docker-compose.yml file:

  • The db service uses the official PostgreSQL image
  • The environment section sets the user, password, and database like before
  • The ports section connects the PostgreSQL port from the container to the host. This allows outside connections

Accessing PostgreSQL

After the container runs, we can connect to the PostgreSQL database using a client like psql or any database tool. We need to provide these connection details:

  • Host: localhost (or the IP of the Docker container)
  • Port: 5432
  • User: myuser
  • Database: mydatabase
  • Password: mypassword

For more help on connecting to PostgreSQL in a Docker container, check this guide.

Using environment variables is a simple way to set up our PostgreSQL instance with Docker. This helps us automate the setup process easily.

Solution 4 - Creating Users and Databases with Docker Compose

We can create users and databases in PostgreSQL using Docker Compose. We define the needed environment variables in our docker-compose.yml file. This way is easier because we can set our database settings directly in the Compose file.

Here is how to set it up:

  1. Create a docker-compose.yml file in our project folder.

  2. Define the PostgreSQL service with the right environment variables for user and database creation.

Here is an example setup:

version: "3.8"

services:
  db:
    image: postgres:latest
    restart: always
    environment:
      POSTGRES_USER: myuser # Change to your username
      POSTGRES_PASSWORD: mypassword # Change to your password
      POSTGRES_DB: mydatabase # Change to your database name
    ports:
      - "5432:5432" # PostgreSQL port
    volumes:
      - postgres_data:/var/lib/postgresql/data # Save data

volumes:
  postgres_data:

Explanation of the Setup

  • image: postgres:latest: This shows the Docker image we use. It is the latest version of PostgreSQL.

  • environment: This part sets the environment variables for PostgreSQL:

    • POSTGRES_USER: The username we want to create.
    • POSTGRES_PASSWORD: The password for this user.
    • POSTGRES_DB: The name of the database we want to create when we start.
  • ports: Here, we map port 5432 so we can access PostgreSQL from our host.

  • volumes: This keeps the PostgreSQL data safe even if we stop or remove the container.

  1. Start the Docker Compose service by running this command in our terminal:
docker-compose up -d

This command starts the services we defined in our docker-compose.yml file in detached mode.

Verifying the Setup

To check if the user and database were created correctly, we can connect to the PostgreSQL container and look at the database settings:

docker exec -it <container_name> psql -U myuser -d mydatabase

We need to change <container_name> with the real name of our PostgreSQL container. This command opens a PostgreSQL prompt. We can run SQL queries there to check if the user and database exist.

For more info on managing our PostgreSQL Docker container, we can look at this guide.

This way of creating users and databases using Docker Compose is simple. It works well with our Docker tasks. Many developers like to use it.

Solution 5 - Managing Permissions for the Created User

After we create a user in our Docker PostgreSQL setup, it is important to manage their permissions. We want to make sure they have the right access to the databases. PostgreSQL uses roles to handle permissions. We can give or take away these roles when we need.

Granting Permissions

To give permissions to a user in PostgreSQL, we can use the GRANT statement. Here is how we do it:

  1. Connect to the PostgreSQL Database: First, we need to connect to our PostgreSQL instance. If we are using Docker, we can do this by running this command:

    docker exec -it <your_postgres_container_name> psql -U <your_superuser>
  2. Grant Permissions: After we connect, we can give different permissions to our user. Here are some common grants:

    • Grant All Privileges on a Database:

      GRANT ALL PRIVILEGES ON DATABASE your_database TO your_user;
    • Grant Specific Privileges on a Table:

      GRANT SELECT, INSERT, UPDATE ON TABLE your_table TO your_user;
    • Grant Usage on a Schema:

      GRANT USAGE ON SCHEMA your_schema TO your_user;

Revoking Permissions

If we need to take away permissions from a user, we can use the REVOKE statement. Here is how:

  • Revoke All Privileges on a Database:

    REVOKE ALL PRIVILEGES ON DATABASE your_database FROM your_user;
  • Revoke Specific Privileges on a Table:

    REVOKE SELECT, INSERT ON TABLE your_table FROM your_user;

Example Script

We can make the process of managing permissions easier by creating a SQL script. For example:

-- Connect to the database
\c your_database;

-- Grant permissions
GRANT ALL PRIVILEGES ON DATABASE your_database TO your_user;
GRANT SELECT, INSERT, UPDATE ON TABLE your_table TO your_user;

-- Revoke permissions
REVOKE INSERT ON TABLE your_table FROM your_user;

Running the Permission Script

To run the script in our Docker PostgreSQL setup:

  1. Save the SQL commands in a file. For example, call it manage_permissions.sql.

  2. Use this command to run the script:

    docker exec -i <your_postgres_container_name> psql -U <your_superuser> -d your_database -f /path/to/manage_permissions.sql

Important Considerations

  • Make sure we have the right privileges to give or take away permissions.
  • Be careful with GRANT ALL PRIVILEGES because it gives users full control over the database.
  • We should regularly check user permissions for security.

For more information on managing PostgreSQL permissions in Docker, we can check resources on connecting to PostgreSQL in Docker or managing Docker containers.

Solution 6 - Verifying User and Database Creation

We want to make sure that the user and database we created in our Docker PostgreSQL setup are working well. You can follow these simple steps to check. This usually means connecting to your PostgreSQL database and looking for the user and database.

Step 1: Connect to PostgreSQL

We can connect to our PostgreSQL instance using the psql command. If we have a running PostgreSQL container, we can use this command to get into the database:

docker exec -it <your_postgres_container_name> psql -U <your_user>

Just replace <your_postgres_container_name> with your PostgreSQL container name. Also, change <your_user> to the username we created. If we are not sure about the container name, we can check it with docker ps.

Step 2: List Databases

After we connect to PostgreSQL, we can list all databases with this SQL command:

\l

This command shows a list of databases. We need to look for the name of the database we made. If we see it there, that means the database was created successfully.

Step 3: Check User Existence

To see if the user exists, we can run this SQL command:

\du

This command lists all users in our PostgreSQL instance. We should check if our created user is in the list.

Step 4: Test User Access

Next, we want to make sure the user has access to the database. We can switch to the database and do a simple task:

\c <your_database_name>

After we switch to the database, we can run this simple query to check if everything is okay:

SELECT current_database();

This should show us the name of the database we switched to. This means the user has access to it.

Step 5: Check Permissions

If we want to make sure that the user has the right permissions on the database, we can check the grants with this SQL command:

SELECT grantee, privilege_type
FROM information_schema.role_table_grants
WHERE table_catalog = '<your_database_name>';

This will show us the permissions the user has on the database we specified.

By following these steps, we can easily verify that the user and database are created in our Docker PostgreSQL setup. If we have problems connecting to PostgreSQL, we can look at this guide on troubleshooting connection issues.

Conclusion

In this article, we looked at different ways to create a user and database in a Dockerized Postgres environment. We talked about using a Dockerfile, SQL scripts, and environment variables. These methods give us more choices and make it easier to manage our Postgres setup in Docker.

If we want to learn more about Docker networking, we can check our guide on managing ports. Also, we can learn more about using Docker Compose to help with application deployment.

Comments