【发布时间】:2019-05-05 17:19:24
【问题描述】:
我有以下设置:
容器中的一个简单 Flask 应用
一个 Postgres 容器
使用以下 Dockerfile:
FROM python:alpine3.7
COPY . /app
WORKDIR /app
RUN apk update
RUN apk add --virtual build-deps gcc python3-dev musl-dev
RUN apk add postgresql-dev
RUN pip install -r requirements.txt
RUN apk del build-deps
EXPOSE 5006
CMD ["python", "./app.py"]
对于数据库:
FROM postgres:11.1-alpine
COPY create_db.sql /docker-entrypoint-initdb.d/
EXPOSE 5432
这是我的 docker-compose yaml(映射到主机以检查容器工作的端口):
version: '3'
services:
postgres:
image: ccdb
build: ccDb
restart: always
environment:
POSTGRES_PASSWORD: password
ports:
- "5432:5432"
top:
image: ccpytop
build: ccPyTop
ports:
- "5006:5006"
我可以从我的主机成功连接到数据库,并且可以导航到 Flask 应用程序提供的应用程序页面。当我导航到某个页面时,应用程序会连接到数据库,因此 postgres 容器有足够的时间启动。
当我运行docker-compose up 时,我得到以下信息:
postgres_1 | 2018-12-04 09:45:13.371 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
postgres_1 | 2018-12-04 09:45:13.371 UTC [1] LOG: listening on IPv6 address "::", port 5432
postgres_1 | 2018-12-04 09:45:13.377 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1 | 2018-12-04 09:45:13.398 UTC [19] LOG: database system was interrupted; last known up at 2018-12-04 09:42:23 UTC
postgres_1 | 2018-12-04 09:45:13.521 UTC [19] LOG: database system was not properly shut down; automatic recovery in progress
postgres_1 | 2018-12-04 09:45:13.524 UTC [19] LOG: redo starts at 0/1680BC8
postgres_1 | 2018-12-04 09:45:13.524 UTC [19] LOG: invalid record length at 0/1680CA8: wanted 24, got 0
postgres_1 | 2018-12-04 09:45:13.524 UTC [19] LOG: redo done at 0/1680C70
postgres_1 | 2018-12-04 09:45:13.536 UTC [1] LOG: database system is ready to accept connections
但是当我在 python 容器中执行以下操作时
>>> import psycopg2
>>> conn = psycopg2.connect("host=/var/run/postgresql dbname=postgres user=postgres password=password")
我明白了:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 130, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
我尝试在没有主机的情况下运行,但收到相同的消息,使用 /tmp/ 而不是 /var/run/。我也尝试过链接容器,但我注意到它是一个遗留功能并且它无论如何都不起作用。
这是我第一次使用 docker-compose,我几乎被困在这一点上。有什么想法吗?
【问题讨论】:
-
为什么主机=/var/run/postgresql ??据我了解,烧瓶应用程序位于不同的容器中...
-
@GioachinoBartolotta 因为我认为它必须匹配 postgres 容器的输出。我的菜鸟错误:)
标签: python postgresql docker docker-compose psycopg2