我对 Docker 还不熟悉,这个项目只是为了帮助我自己理解它。我可能使用了不正确的术语,或者比我认为的更加困惑。非常感谢你的纠正。
我正在使用两个 Docker 镜像:官方的 Postgres 镜像和我自己的 Go 应用程序和 Dockerfile。使用 docker-compose up
命令时,我遇到了 connection refused
错误。
我认为可能有两个不同的问题:
一,当应用程序尝试连接时,数据库未在运行。
二,应用程序简单地使用了无效的 IP 地址。
我有一段应用程序代码,应该能够给数据库启动足够的时间以解决第一个潜在的问题(请参见下面的代码)。根据错误消息,我认为我甚至还没有达到那一步。
我有两个服务:db-access(即 Go 应用程序)和 postgres-db。
我已经尝试在应用程序连接字符串中使用以下主机名:
"localhost"
"postgres-db"(在 docker-compose.yml 中命名的名称)
"0.0.0.0"
使用 postgres-db
作为主机名:
应用程序容器正在尝试:拨号 tcp 172.22.0.2:5432。
Postgres 正在说:监听 IPv4 地址 "0.0.0.0",端口 5432。
在 docker-compose.yml
中,我已经尝试使用以下语句:
depends_on:
- postgres-db
并且
links:
- postgres-db
我尝试过改变docker-compose.yml文件中服务的顺序,但无论如何它们都会以相同的顺序启动。当我分别运行postgres容器和Go应用程序时,我得到了期望的结果。为了分别运行它们,我使用以下命令:
docker run --rm --name postgres-db -e POSTGRES_PASSWORD=docker -d -p 5432:5432 -v /Users/ForeignFood/Development/go/src/github.com/skillitzimberg/docker/volumes/postgres:/var/lib/postgresql/data postgres
紧随其后
go run basicapi
我还可以运行docker-compose up
,但是会出现连接被拒绝的错误,然后按ctrl+C
退出,接着运行go run basicapi
就能得到预期的结果。
以下是项目文件...
main.go:
package main
import (
"basicapi/models"
"fmt"
"net/http"
_ "github.com/lib/pq"
)
const (
host = "postgres-db"
port = 5432
user = "postgres"
password = "docker"
dbname = "myfirstdb"
)
var psqlDatabaseConnectionString = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
func main() {
models.InitDB(psqlDatabaseConnectionString)
http.HandleFunc("/users", usersList)
http.ListenAndServe(":3000", nil)
}
func usersList(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(405), 405)
return
}
usrs, err := models.AllUsers()
if err != nil {
fmt.Println(err)
http.Error(w, http.StatusText(500), 500)
return
}
for _, usr := range usrs {
fmt.Fprintf(w, "%d, %s, %s, %.s\n", usr.ID, usr.FirstName, usr.LastName, usr.Email)
}
}
models/db.go:
package models
import (
"database/sql"
"fmt"
"log"
"time"
_ "github.com/lib/pq"
)
var db *sql.DB
func InitDB(dataSourceName string) {
var err error
for i := 0; i < 10; i++ {
db, err = sql.Open("postgres", dataSourceName)
if err != nil {
fmt.Println(i)
fmt.Println(err)
time.Sleep(time.Second * 10)
}
}
if err != nil {
log.Panic(err)
}
if err = db.Ping(); err != nil {
log.Panic(err)
}
fmt.Printf("Connection to database successful!\n")
}
models/users.go:
package models
import "fmt"
type User struct {
ID int
Age int
FirstName string
LastName string
Email string
}
func AllUsers() ([]*User, error) {
fmt.Println("Got to AllUsers")
rows, err := db.Query("SELECT * FROM users")
if err != nil {
fmt.Println(err)
return nil, err
}
defer rows.Close()
users := make([]*User, 0)
for rows.Next() {
user := new(User)
err := rows.Scan(&user.ID, &user.Age, &user.FirstName, &user.LastName, &user.Email)
if err != nil {
return nil, err
}
users = append(users, user)
}
if err = rows.Err(); err != nil {
return nil, err
}
return users, nil
}
Dockerfile:
FROM golang
WORKDIR /app
COPY ./go.mod ./go.mod
COPY ./go.sum ./go.sum
RUN go mod download
COPY . .
RUN go build -o /bin/app
CMD [ "app" ]
docker-compose.yml
services:
db-access:
build: .
depends_on:
- postgres-db
ports:
- "3000:3000"
postgres-db:
image: postgres
volumes:
- /Users/ForeignFood/Development/go/src/github.com/skillitzimberg/docker/volumes/postgres:/var/lib/postgresql/data
ports:
- "5432:5432"
environment:
POSTGRES_USER: "postgres"
POSTGRES_PASSWORD: "docker"
POSTGRES_DATABASE: "myfirstdb"
预期结果: 导航至 localhost:3000/users 显示:
1, Someone, Alastname,
2, SomeoneElse, AnotherLastName,
etc...
实际结果:
浏览器:
该网站无法访问
终端:
~/ >> docker-compose up
Starting basicapi_postgres-db_1 ... done
Starting basicapi_db-access_1 ... done
Attaching to basicapi_postgres-db_1, basicapi_db-access_1
db-access_1 | 2019/05/17 16:53:54 dial tcp 172.22.0.2:5432: connect: connection refused
db-access_1 | panic: dial tcp 172.22.0.2:5432: connect: connection refused
db-access_1 |
db-access_1 | goroutine 1 [running]:
db-access_1 | log.Panic(0xc0000c3f40, 0x1, 0x1)
db-access_1 | /usr/local/go/src/log/log.go:333 +0xac
db-access_1 | basicapi/models.InitDB(0xc000062120, 0x55)
db-access_1 | /app/models/db.go:30 +0x27c
db-access_1 | main.main()
db-access_1 | /app/main.go:23 +0x3d
basicapi_db-access_1 exited with code 2
postgres-db_1 | 2019-05-17 16:53:58.770 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
postgres-db_1 | 2019-05-17 16:53:58.770 UTC [1] LOG: listening on IPv6 address "::", port 5432
postgres-db_1 | 2019-05-17 16:53:58.776 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres-db_1 | 2019-05-17 16:53:58.905 UTC [22] LOG: database system was shut down at 2019-05-17 16:53:23 UTC
postgres-db_1 | 2019-05-17 16:53:58.952 UTC [1] LOG: database system is ready to accept connections
感谢您提供的任何见解。
host.docker.internal
而非localhost
。 - KinaneD