3

I'm trying to run a golang server at localhost:8080 that uses a postgres database. I've tried to containerize both the db and the server but can't seem to get them connected.

main.go

func (a *App) Initialize() {
    var db *gorm.DB
    var err error
    envErr := godotenv.Load(".env")
    if envErr != nil {
        log.Fatalf("Error loading .env file")
    }
    var dbString = fmt.Sprintf("port=5432 user=sample dbname=sampledb sslmode=disable password=password host=db")
    
    db, err = gorm.Open("postgres", dbString)
    if err != nil {
        fmt.Printf("failed to connect to databse\n",err)
    }
    a.DB=model.DBMigrate(db)
    a.Router = mux.NewRouter()
    a.setRoutes()
}

//Get : get wrapper
func (a *App) Get(path string, f func(w http.ResponseWriter, r *http.Request)) {
    a.Router.HandleFunc(path, f).Methods("GET")
}

//Post : post wrapper
func (a *App) Post(path string, f func(w http.ResponseWriter, r *http.Request)) {
    a.Router.HandleFunc(path, f).Methods("POST")
}

//Run : run on port
func (a *App) Run(port string) {
    handler := cors.Default().Handler(a.Router)
    log.Fatal(http.ListenAndServe(port, handler))
}

func (a *App) setRoutes() {
    a.Get("/", a.handleRequest(controller.Welcome))
    a.Get("/users", a.handleRequest(controller.GetUsers))
    a.Get("/user/{id}", a.handleRequest(controller.GetUser))
    a.Post("/login", a.handleRequest(controller.HandleLogin))
    a.Post("/users/add", a.handleRequest(controller.CreateUser))
    a.Post("/validate", a.handleRequest(controller.HandleValidation))
}

func main() {
    app := &App{}
    app.Initialize()
    app.Run(":8080")

}


server Dockerfile

FROM golang:latest

RUN mkdir /app
WORKDIR /app/server

COPY go.mod .
COPY go.sum .
RUN go mod download
COPY . .

docker-compose.yml

version: '3.7'
services:
    db:
        image: postgres
        container_name: ep-db
        environment:
            - POSTGRES_PORT=${DB_PORT}
            - POSTGRES_USER=${DB_USERNAME}  
            - POSTGRES_PASSWORD=${DB_PASSWORD}
            - POSTGRES_DB=${DB_NAME}
            
        ports:
            - '5432:5432'
        volumes:
            - ./db:/var/lib/postgresql/data"
        networks:
            - internal
    server:
        container_name: ep-server
        build:
            context: ./server
            dockerfile: Dockerfile
        command: bash -c "go build && ./server -b 0.0.0.0:8080 --timeout 120"
        volumes:
            - './server:/app/server'
        expose:
            - 8080
        depends_on: 
            - db
        networks:
            - internal
        stdin_open: true
volumes:
    db:  
    server:
networks:
    internal:
      driver: bridge

I have some get and post requests that return the right values when i run it locally on my computer (for ex. localhost:8080/users would return a JSON full of users from the database) but when I use curl inside the server container, I don't get any results. I am new to docker, Is there something wrong with what I'm doing so far?

3
  • 2
    What do you get? Are there any errors in the container logs? Do you need to declare ports: for your server container, so that it's reachable from outside Docker? Commented May 5, 2021 at 23:13
  • try adding hostname to your database in docker compose and use that name for connecting in code. Commented May 5, 2021 at 23:14
  • What are the errors you get? Commented May 7, 2021 at 12:10

2 Answers 2

3

Each docker container has its own IP address. When you connect to the postgres db from your application, you are using localhost, which is the container for the application and not the db. Based on your docker-compose, you should use the hostname db (the service name) to connect to the database.

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

Comments

1

As suggested by @DavidMaze you should verify the logs from your server container. Also,

  1. First ensure ep-server is running (check that the output of docker container ls has status running for ep-server)
  2. Run docker logs ep-server to view errors (if any)
  3. If there are no errors in the logs, then run a docker exec -it ep-server bash to login to your container and run a telnet ep-db 5432 to verify that your postgres instance is reacheable from ep-server

Comments

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.