当Docker脚本中的Python连接到堆栈中的SQL Server时出现问题

时间:2019-01-27 21:49:48

标签: postgresql docker docker-swarm docker-networking docker-stack

我有一个堆栈,可以很好地发挥作用(至少我认为它可以...)。它在端口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容器中的db开始:

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

很显然,我希望从网络外部访问数据库比从内部访问数据库更加困难,所以很明显,我在这里错过了一些东西,但是我不知道...

1 个答案:

答案 0 :(得分:1)

当使用Compose文件部署堆栈时,网络的全名是通过将堆栈名称与基本网络名称组合在一起来创建的。因此,假设您像这样部署了名称为foo的堆栈。

docker stack deploy -c compose-file.yml foo

然后,完整的网络名称将为foo_service_network

运行Python容器时,需要将其连接到foo_service_network,而不是service_network

docker container run --rm --net foo_service_network -t UnitTest-image py.test /testing

您还可以通过在Compose文件(版本3.5及更高版本)中指定name属性来自定义网络名称。

networks:
  service_network:
    name: service_network

在这种情况下,您将使用该自定义名称将容器连接到网络。

docker container run --rm --net service_network -t UnitTest-image py.test /testing

编辑1/28:添加了撰写文件示例。

version: "3.7"
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:
    name: service_network
    attachable: true