首页 > 解决方案 > Docker + Postgres 无法使配置工作

问题描述

我刚刚开始使用 docker,但无法让我的 API 连接到我的数据库。我得到一个connection refused.

我在日志中得到了这个,这似乎意味着环境变量没有被传入:The files belonging to this database system will be owned by user "postgres".

docker exec -ti [container_id] psql -U postgres但是,也有效docker exec -ti [container_id] psql -U docker->role "docker" does not exist

我也尝试COPY在数据库中创建一个 init.sql 文件Dockerfile,但它似乎没有任何效果。

这是我的docker-compose.yaml。有什么明显的错误吗?

version: '2'
services:
  db:
    build: ./db
    volumes:
      - ./db/pgdata:/pgdata
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_USER=docker
      - POSTGRES_PASSWORD=docker
      - POSTGRES_DB=xx
      - PGDATA=/pgdata

  api:
    build:
      context: .
      args:
        app_env: ${APP_ENV}
    volumes:
      - .:/go/src/github.com/x/xx
    ports:
      - "5000:8080"
    links:
      - db

这是我的 Dockerfile

FROM golang
ARG app_env
ENV APP_ENV $app_env

# Copy the local package files to the container's workspace
COPY . /go/src/github.com/x/xx
WORKDIR /go/src/github.com/x/xx

# added vendor services will need to be included here
RUN go build

# if dev setting will use pilu/fresh for code reloading via docker-compose volume sharing with local machine
# if production setting will build binary
CMD if [ ${APP_ENV} = production ]; \
    then \
    api; \
    else \
    go get github.com/pilu/fresh && \
    fresh -c recompile.conf; \
    fi

# Document that the container uses port 8080
EXPOSE 8080

这是我在 ./db 下的 Dockerfile

FROM postgres:latest
EXPOSE 5432

标签: postgresqldockerdocker-compose

解决方案


据我所知,这似乎是一个网络问题。没有完整的范围很难调试你的文件,所以这里是关于内部网络以及如何允许容器之间连接的文档。

此外,这是一个完整docker-compose.yml的 Postgres 数据库和一个桥接网络:

version: '3.1'

services:

  postgres:
    container_name: postgres
    image: postgres:11-alpine
    network_mode: bridge
    volumes:
      - ./data:/var/lib/postgresql/data
    ports:
      - 5432:5432
    environment:
      - "POSTGRES_PASSWORD=whatever"

  clientApp:
    container_name: cinema
    image: your/image:latest
    network_mode: bridge
    external_links:
      - postgres

推荐阅读