2

I am Trying to dockerize my golang rest api with docker-compose.yml file.

Suppose currently I dont have any docker images. I just

run docker-compose up -d

It automatically creates 2 docker images 1 of database and 1 of the code.

But when I see the log by running command

docker-compose logs

I get these logs

Attaching to posty-api_api_1, postgres
postgres    | 
postgres    | PostgreSQL Database directory appears to contain a database; Skipping initialization
postgres    |
postgres    | 2021-06-14 07:37:46.437 UTC [1] LOG:  starting PostgreSQL 13.3 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.2.1_pre1) 10.2.1 20201203, 64-bit
postgres    | 2021-06-14 07:37:46.438 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres    | 2021-06-14 07:37:46.438 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres    | 2021-06-14 07:37:46.481 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres    | 2021-06-14 07:37:46.607 UTC [22] LOG:  database system was shut down at 2021-06-14 07:33:40 UTC
postgres    | 2021-06-14 07:37:46.696 UTC [1] LOG:  database system is ready to accept connections
api_1       | main.go start
api_1       | database.go START
api_1       |
api_1       | 2021/06/14 07:37:45 /app/database/database.go:23
api_1       | [error] failed to initialize database, got error failed to connect to `host=postgres user=postgres database=postgres`: dial error (dial tcp 172.22.0.2:5432: connect: connection refused)
api_1       | panic: failed to connect database
api_1       |
api_1       | goroutine 1 [running]:
api_1       | github.com/usman-174/database.ConnectDataBase(0xc0001ae2f0)
api_1       |   /app/database/database.go:26 +0x49a
api_1       | github.com/usman-174/app.Router(0xa7c120)
api_1       |   /app/app/app.go:10 +0x26
api_1       | main.main()
api_1       |   /app/main.go:16 +0x9b

I cant connect with the data base. Even I provide correct env variables.

This is my .env file:

DSN=host=postgres user=postgres password=postgres dbname=postgres port=5432 sslmode=disable
CLIENT_URL=https://clever-montalcini-cedd07.netlify.app/
PORT=:8080

This is my dockerfile:

FROM golang:1.16.5-alpine3.13 AS builder
WORKDIR /app
COPY . .
RUN go build -o main main.go

# Run stage
FROM alpine:3.13
WORKDIR /app
COPY --from=builder /app/main .
COPY .env .
EXPOSE 8080

This is my docker-compose.yml file:

# Specify the version for docker-compose.yml
version: "3.8"

# add the serivces needed (postgres,go)
services:
  postgres:
    container_name: postgres
    image: postgres:13-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: auth
      # Optional: Give a name to the database, otherwise
      # use the default value POSTGRES_USER as a database name (user in this case.)
      POSTGRES_DB: auth
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5
    ports:
      - "5432:5432"
    volumes:
      - ./pgdata:/var/lib/postgresql/data

  api:
    build:
      context: .
      dockerfile: Dockerfile
    command: ["./wait-for-it.sh", "postgres:5432", "--", "/app/main" ]
    ports:
      - "8080:8080"
    depends_on:
      - postgres
    command: [ "/app/main" ]

And this is how I connect to my database:

func ConnectDataBase() *gorm.DB {
fmt.Println("database.go START")
err := godotenv.Load()

if err != nil {
    log.Fatal("Error loading .env file")
}
dsn := os.Getenv("DSN")
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

if err != nil {
    panic("failed to connect database")
}
db.AutoMigrate(&models.User{})
db.AutoMigrate(&models.Post{})
db.AutoMigrate(&models.Like{})
fmt.Println("database.go STOP")

return db
}
2
  • 2
    Just login to the api container using docker exec -it <container id> /bin/sh and then run curl or ping the postgress container with its name i.e postgress. See if you can reach the db. In docker-compose a default network is created and all containers are placed in the default network. So the postgress db should be accessible Commented Jun 14, 2021 at 8:49
  • I can get a connection this is the response: 64 bytes from 172.23.0.2: seq=28 ttl=64 time=0.074 ms 64 bytes from 172.23.0.2: seq=29 ttl=64 time=0.068 ms 64 bytes from 172.23.0.2: seq=30 ttl=64 time=0.062 ms Commented Jun 14, 2021 at 9:02

1 Answer 1

4

Seems like the database name on the DSN is incorrect.

On your docker-compose.yml it's:

POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: auth
...

meanwhile, on your .env it's:

DSN=host=postgres user=postgres password=postgres dbname=postgres ...

try to use dbname=auth instead of dbname=postgres on the .env file

Sign up to request clarification or add additional context in comments.

3 Comments

Like this in docker-compose.yml: environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DBNAME: auth
I mean, since in your docker-compose.yml the db is auth, then on your .env it should be DSN=host=postgres user=postgres password=postgres dbname=auth port=5432 sslmode=disable
If this solution works, probably this answer can be accepted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.