如何在一个Docker容器中运行python应用程序和postgres? [英] How to run the python application and postgres in one docker container?

查看:50
本文介绍了如何在一个Docker容器中运行python应用程序和postgres?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a python application that interacts with the postgresql database and i need to run it all in one docker container. I get a connection error when running the container:

  ...

  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"]

推荐答案

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

Although this is not recommended, it's doable. The problem is pg_ctl in RUN instruction is executed at build time, not in the container. You need to run it with CMD.

您可以使用类似的脚本

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

COPY 图像中和dockerfile末尾脚本"CMD ["./script.sh"]

COPY the script in the image and at the end of the dockerfile, `CMD ["./script.sh"]

这篇关于如何在一个Docker容器中运行python应用程序和postgres?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆