简体   繁体   中英

Connecting Golang and Postgres docker containers

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM