简体   繁体   English

连接 Golang 和 Postgres docker 容器

[英]Connecting Golang and Postgres docker containers

I'm trying to run a golang server at localhost:8080 that uses a postgres database.我正在尝试在 localhost:8080 上运行一个使用 postgres 数据库的 golang 服务器。 I've tried to containerize both the db and the server but can't seem to get them connected.我试图将数据库和服务器都容器化,但似乎无法将它们连接起来。

main.go主.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服务器 Dockerfile

FROM golang:latest

RUN mkdir /app
WORKDIR /app/server

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

docker-compose.yml 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.当我在我的计算机上本地运行它时,我有一些 get 和 post 请求返回正确的值(例如 localhost:8080/users 将返回一个 JSON 完整的数据库用户)但是当我在服务器容器内使用 curl 时,我没有得到任何结果。 I am new to docker, Is there something wrong with what I'm doing so far?我是 docker 的新手,到目前为止我在做什么有问题吗?

Each docker container has its own IP address.每个 docker 容器都有自己的 IP 地址。 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.当您从应用程序连接到 postgres 数据库时,您使用的是localhost ,它是应用程序的容器,而不是数据库。 Based on your docker-compose, you should use the hostname db (the service name) to connect to the database.根据您的 docker-compose,您应该使用主机名db (服务名称)连接到数据库。

As suggested by @DavidMaze you should verify the logs from your server container.正如@DavidMaze 所建议的,您应该验证服务器容器中的日志。 Also,还,

  1. First ensure ep-server is running (check that the output of docker container ls has status running for ep-server )首先确保ep-server正在运行(检查docker 容器 ls的 output 的状态是否为ep-server运行)
  2. Run docker logs ep-server to view errors (if any)运行docker logs ep-server查看错误(如果有)
  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如果日志中没有错误,则运行docker exec -it ep-server bash登录到您的容器并运行telnet ep-db 5432以验证您的 postgres 实例是否可以从 ep-server 访问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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