我有以下设置:
容器中的一个简单 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,此时我几乎陷入困境。有任何想法吗?