不能为docker中的postgres添加模式

我试图在Docker中构build一个包含nginx,postgresql和php-fpm的debian镜像。 我设法让nginx和php-fpm工作。 Postgres也在工作,但我不能将模式添加到我创build的数据库。

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

还有另一种方法可以做到这一点,我没有看到? 我需要做更多的事情吗?

你不能连接到服务器的原因是因为它没有运行。 Dockerfile中的每一行都在一个新的容器中进行处理,所以任何旧的进程都不再运行,但是文件系统的改变将会持续下去(假设它们没有被创build到一个卷上)。

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

到目前为止,最好的计划是像@ h3nrikbuild议的那样使用官方的postgres镜像。 即使你不想这样做,值得看Dockerfile和脚本(例如https://github.com/docker-library/postgres/tree/master/9.5 )用于构build官方图像,以了解如何他们解决了同样的问题。

我不会把nginx和postgres安装在一个docker容器中。 我会创build一个单独的postgres容器,并从nginx / php-fpm容器链接到它。

postgres容器我会基于官方的 。 在那里还介绍了如何将自定义模式添加到postgres安装中(请参考justfalter的评论)。