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 run
The fundamental command to create and start containers.--name postgres-container
Assigns a specific name to the container.-e POSTGRES_PASSWORD=yourpassword
Sets the PostgreSQL password using an environment variable.-e POSTGRES_USER=postgres
Specifies the PostgreSQL user.-d
Runs the container in detached mode (in the background).postgres
Specifies 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
services
Lists the services to be managed by Docker Compose. In this case, only postgres is defined.image
Specifies the Docker image to use (e.g., postgres:15).container_name
Defines the name of the container.environment
Sets environment variables such as database name, user, and password.volumes
Maps container directories to local directories for persistent storage.ports
Maps container ports to local ports. The format is local_port : container:port.networks
Specifies 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.