我有一堆单独运行良好的堆栈(至少我认为它确实......)。它有一个在端口 5432 上工作的 postgresql 和一个在端口 80 上的 web 服务器。可以从外部正确访问 web 服务器。
对于单元测试,我仅以堆栈模式运行数据库端:
version: "3"
services:
sql:
image: sql
networks:
- service_network
ports:
- 5432:5432
deploy:
replicas: 1
restart_policy:
condition: on-failure
volumes:
- ./local_storage_sql:/var/lib/postgresql/data
environment:
# provide your credentials here
- POSTGRES_USER=xxxx
- POSTGRES_PASSWORD=xxxx
networks:
service_network:
然后,单元测试首先连接到另一个简单 python 容器中的数据库:
FROM python:latest
LABEL version="0.1.0"
LABEL org.sgnn7.name="unittest"
# Make sure we are fully up to date
RUN apt-get update -q && \
apt-get dist-upgrade -y && \
apt-get clean && \
apt-get autoclean
RUN python -m pip install psycopg2-binary
RUN mkdir /testing
COPY ./*.py /testing/
连接时测试脚本失败:
conn = connect(dbname=database, user=user, host=host, password=password)
和:
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: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
但只有当我在容器内运行它时它才会失败。从外面看,它就像一个魅力。我还尝试设置一个外部网络并使用它(相同的 docker 节点):
docker run --rm --net service_network -t UnitTest-image py.test /testing
显然,我预计从网络外部访问数据库比从内部访问数据库更困难,所以很明显,我在这里错过了一些东西,但我不知道是什么......