Postgres Containers with Docker
- #Docker
- #PostgreSQL
In this guide i want to explain how can we set up a simple PostgreSQL container using two methods: directly through the Docker CLI and using a Docker Compose file.
Additionally, we’ll cover some basic commands for managing your containers.
Method 1: Creating a Container Using the Docker CLI
You can create a PostgreSQL container directly from the command line using the following command:
$ docker run --name postgres-container -e POSTGRES_PASSWORD=yourpassword -e POSTGRES_USER=postgres -d postgres
Explanation of the Command
docker runThe fundamental command to create and start containers.--name postgres-containerAssigns a specific name to the container.-e POSTGRES_PASSWORD=yourpasswordSets the PostgreSQL password using an environment variable.-e POSTGRES_USER=postgresSpecifies the PostgreSQL user.-dRuns the container in detached mode (in the background).postgresSpecifies the image name to be used for creating the container.
Key Notes:
- Flags: Options used to define container characteristics. For instance, -e sets environment variables, while --name specifies the container name.
Method 2: Using a Docker Compose File
For better organization and visibility, you can use a Docker Compose file. Create a file named docker-compose.yml with the following content:
services:
postgres:
image: postgres:15
container_name: ${POSTGRES_CONTAINER_NAME}
environment:
POSTGRES_DB: keycloak
POSTGRES_USER: admin
POSTGRES_PASSWORD: admin
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "${POSTGRES_PORT:-5432}:5432"
networks:
- keycloak_network
Explanation of docker-compose.yml
servicesLists the services to be managed by Docker Compose. In this case, only postgres is defined.imageSpecifies the Docker image to use (e.g., postgres:15).container_nameDefines the name of the container.environmentSets environment variables such as database name, user, and password.volumesMaps container directories to local directories for persistent storage.portsMaps container ports to local ports. The format is local_port : container:port.networksSpecifies the network configuration.
If you are using a docker-compose.yml file you will need tthe command below to execute it, make sure you are in the same location as your docker-compose file and type:
$ docker compose up
This will start your services right on. Similar to it we can take our containers down with:
$ docker compose down
Managing Docker Containers
Here are some essential commands for managing your containers:
Accessing a Container
$ docker exec -it <container_name_or_id> sh
Viewing Logs of a Container
$ docker logs <container_name_or_id>
Stopping a Container
$ docker stop <container_name_or_id>
Starting a Container
$ docker start <container_name_or_id>
Removing a Container
$ docker rm <container_name_or_id>
By using these methods and commands, you can easily set up and manage PostgreSQL containers.



