Skip to content

Using Postgresql in Docker

Posted on:December 3, 2024 at 01:01 PM

After I learned Docker, I never installed postgresql server, mysql server, web server and something like that anymore on my machine, but I dockerized it. It makes my machine more clean and easier to debug.

You can just make docker compose, and run the compose, and that server will run. Without make our machine “dirty”.

Here’s my docker compose example for my postgresql service container

version: '3.9'

services:

  postgres:
    container_name: postgres
    image: postgres:17.2-alpine
    restart: always
    shm_size: 128mb
    environment:
        POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
    volumes:
      - db_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"

secrets: 
  db_password: 
    file: ./password.txt

volumes:
  db_data:

and the secret file password.txt

gajiguruhonorer

I use secrets because Docker recommends to store any sensitive information or data, such as password, certificate, etc in container.

The secret file is located in the same directory as the compose.yml file. It will mounted to /run/secrets/(secret name) inside the container, so when we define our environment, we use POSTGRES_PASSWORD_FILE with the value from the secret mounting.