How to make postgres listen on the container's new exposed port (not 5432)?

Issue

I try to initialize a database with Go.
I use port 5433 at postgres:alpine because 5432 is already taken by another microservice app.

func Init() {
    DB, err = gorm.Open(postgres.New(postgres.Config{
        DSN: "host=url_db user=gorm password=gorm dbname=gorm port=5433 sslmode=disable TimeZone=Asia/Tokyo",
    }), &gorm.Config{})
    if err != nil {
        panic(err)
    }
    autoMigration()
}
  url_db:
    build: 
      context: ./api/services/url/db
      dockerfile: Dockerfile
    container_name: "url_db"
    environment: 
      POSTGRES_USER: gorm
      POSTGRES_PASSWORD: gorm
      POSTGRES_DB: gorm
      POSTGRES_HOST: url_db
    ports:
      - 5433:5433

You can confirm that only 5432 is exposed here.

I tried to expose 5433 by creating a new Dockerfile like this.

FROM postgres:alpine
EXPOSE 5433

But I got this error.

failed to initialize database, got error failed to connect to `host=url_db user=gorm database=gorm`: dial error (dial tcp 172.19.0.3:5433: connect: connection refused)

This comment:

Simply exposing the port on the docker image won’t do anything unless postgres is actually configured to listen on that port. – super 5 mins ago

that teaches me the title(How can I expose a new port(not 5432) at postgres:alpine image?) is not the point, so I updated the title.

How to make postgres listen on the container’s new exposed port (not 5432)?

Solution

You have multiple options:

Option 1: Define own postgresql.conf

  url_db:
    build: 
      context: ./api/services/url/db
      dockerfile: Dockerfile
    container_name: "url_db"
    command: postgres -c "config_file=/etc/postgresql/postgresql.conf"
    environment: 
      POSTGRES_USER: gorm
      POSTGRES_PASSWORD: gorm
      POSTGRES_DB: gorm
      POSTGRES_HOST: url_db
    ports:
      - 5433:5433
    volumes:
      - /path/to/config:/etc/postgresql/postgresql.conf

Postgres has an example config at /usr/share/postgresql/postgresql.conf.sample within the container.

To get the config run:

docker run -i --rm postgres cat /usr/share/postgresql/postgresql.conf.sample > my-postgres.conf

Option 1: Overwrite the RUN command

  url_db:
    build: 
      context: ./api/services/url/db
      dockerfile: Dockerfile
    container_name: "url_db"
    command: postgres -c port=5433
    environment: 
      POSTGRES_USER: gorm
      POSTGRES_PASSWORD: gorm
      POSTGRES_DB: gorm
      POSTGRES_HOST: url_db
    ports:
      - 5433:5433

Answered By – Spirit

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.