【问题标题】:Can't add schema for postgres inside docker无法在 docker 中为 postgres 添加架构
【发布时间】:2015-07-25 17:36:56
【问题描述】:

我正在尝试在 Docker 中构建一个包含 nginx、postgresql 和 php-fpm 的 debian 映像。我已经设法让 nginx 和 php-fpm 工作。 Postgres 也在工作,但我无法将架构添加到我创建的数据库中。

Dockerfile 中与 postgres 相关的代码(从 docker 网站获得)如下:

# Add database
RUN apt-get update && apt-get install -y postgresql-9.4 postgresql-client-9.4 postgresql-contrib-9.4
# Run the rest of the commands as the ``postgres`` user created by the ``postgres-9.4`` package when it was ``apt-get installed``
USER postgres

# Create a PostgreSQL role named ``use_name`` with ``user_password`` as the password and
# then create a database `database_name` owned by the ``use_name`` role.
# Note: here we use ``&&\`` to run commands one after the other - the ``\``
#       allows the RUN command to span multiple lines.
RUN    /etc/init.d/postgresql start &&\
    psql --command "CREATE USER user_name WITH SUPERUSER PASSWORD 'user_password';" &&\
    createdb -O user_name database_name

# Adjust PostgreSQL configuration so that remote connections to the
# database are possible. 
RUN echo "host all  all    0.0.0.0/0  md5" >> /etc/postgresql/9.4/main/pg_hba.conf

# And add ``listen_addresses`` to ``/etc/postgresql/9.4/main/postgresql.conf``
RUN echo "listen_addresses='*'" >> /etc/postgresql/9.4/main/postgresql.conf

# Reload postgres configuration
RUN /etc/init.d/postgresql stop && /etc/init.d/postgresql start

# Add database schema
COPY ./postgresql/database_name.sql /tmp/database_name.sql
RUN psql -U use_name -d database_name -a -f /tmp/database_name.sql

我得到的错误是

psql: could not connect to server: Connection refused
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

还有其他我没见过的方法吗?我需要做更多的事情吗

【问题讨论】:

    标签: postgresql docker


    【解决方案1】:

    您无法连接到服务器的原因是它没有运行。 Dockerfile 中的每一行都在一个新容器中处理,因此任何旧进程都不再运行,但对文件系统的更改将持续存在(前提是它们不是针对卷进行的)。

    您可以在与 psql 命令相同的 RUN 指令中启动数据库,但通常这类事情将在容器启动时运行的 ENTRYPOINTCMD 脚本中完成。

    到目前为止,最好的计划是按照@h3nrik 的建议进行操作,并使用官方的postgres 图像。即使您不想这样做,也值得查看用于构建官方镜像的 Dockerfile 和脚本(例如 https://github.com/docker-library/postgres/tree/master/9.5),以了解它们如何解决相同的问题。

    【讨论】:

    • 嘿,谢谢你的回答,我试过链接容器但我没能成功,你知道一个很好的教程吗?我做了所有的步骤,但我不能让它工作:(
    • 是的,我做到了,在链接了几个容器后没有任何效果......我想我需要继续尝试
    • 如果某些特定的东西不像您认为的那样有效,请提出一个新问题。
    • 我正在尝试构建一个 LEMP,但使用的是 postgres 而不是 mysql,我尝试使用现有容器并使用基于 debian 的容器自己构建它们。当我完成这个过程时,我无法通过浏览器访问 nginx 服务器......而且我发现有些容器很难使用,我想我只需要多尝试一下
    【解决方案2】:

    我不会将 nginx 和 postgres 安装放在一个 docker 容器中。我会从 nginx/php-fpm 容器中创建一个单独的 postgres 容器和 link

    我将基于 official one 的 postgres 容器。那里还描述了如何将自定义架构添加到 postgres 安装中(请查看 justfalter 的评论)。

    【讨论】:

    • 谢谢,我正在尝试通过链接容器来使其工作,但我无法使其工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2015-06-10
    • 2021-10-16
    • 1970-01-01
    • 2015-08-22
    相关资源
    最近更新 更多