【问题标题】:How to run the python application and postgres in one docker container?如何在一个 docker 容器中运行 python 应用程序和 postgres?
【发布时间】:2019-01-16 21:06:44
【问题描述】:

我有一个与 postgresql 数据库交互的 python 应用程序,我需要在一个 docker 容器中运行它。 运行容器时出现连接错误:

  ...

  File "/usr/lib/python3.6/asyncio/tasks.py", line 358, in wait_for
    return fut.result()
  File "/usr/lib/python3.6/asyncio/base_events.py", line 787, in create_connection
    ', '.join(str(exc) for exc in exceptions)))
OSError: Multiple exceptions: [Errno 111] Connect call failed ('::1', 5432), [Errno 111] Connect call failed ('127.0.0.1', 5432)

我的Dockerfile

FROM postgres:10.0-alpine
RUN apk add --update --no-cache g++ alpine-sdk
RUN apk --no-cache add python3-dev
RUN apk add --no-cache python3 && \
    python3 -m ensurepip && \
    rm -r /usr/lib/python*/ensurepip && \
    pip3 install --upgrade pip setuptools && \
    if [ ! -e /usr/bin/pip ]; then ln -s pip3 /usr/bin/pip ; fi && \
    if [[ ! -e /usr/bin/python ]]; then ln -sf /usr/bin/python3 /usr/bin/python; fi && \
    rm -r /root/.cache    
ADD app /app/   
RUN chmod -R 777 /app 
WORKDIR /app
ADD requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
USER postgres
RUN chmod 0700 /var/lib/postgresql/data &&\
    initdb /var/lib/postgresql/data &&\
    echo "host all  all    0.0.0.0/0  md5" >> /var/lib/postgresql/data/pg_hba.conf &&\
    echo "listen_addresses='*'" >> /var/lib/postgresql/data/postgresql.conf &&\
    pg_ctl start &&\
    psql --command "ALTER USER postgres WITH ENCRYPTED PASSWORD 'postgres';"
EXPOSE 5432
EXPOSE 80
CMD ["python3", "main.py"]

【问题讨论】:

    标签: postgresql docker


    【解决方案1】:

    虽然不建议这样做,但它是可行的。问题是RUN 中的pg_ctl 指令是在构建时执行的,而不是在容器中执行的。您需要使用CMD 运行它。

    你可以有这样的脚本

    pg_ctl start
    psql --command "ALTER USER postgres WITH ENCRYPTED PASSWORD 'postgres';"
    python3 main.py
    

    COPY镜像中和dockerfile末尾的脚本,`CMD ["./script.sh"]

    【讨论】:

      【解决方案2】:

      @Anton,不建议在 docker 容器内运行多个进程。看看这个链接https://docs.docker.com/config/containers/multi-service_container/ 它将解释更多并展示实现这一点的方法。您可能知道,但是您的容器将运行 postgresql 实例并在其中包含数据,因此如果您重新创建容器,您将丢失该容器中的所有数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-09
        • 1970-01-01
        • 2021-01-05
        • 2015-07-16
        相关资源
        最近更新 更多