我有一个Python / PostgreSQL项目我试图放入Docker容器。 当我尝试在容器内运行psql命令以在构建映像时创建用户和数据库时,我收到此错误:
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
这是一个Dockerfile:
FROM python:2.7-slim
WORKDIR /app
ADD . /app
RUN apt-get update && apt-get install -y postgresql postgresql-contrib libgeos-c1
RUN service postgresql start
RUN su postgres bash -c "psql -c \"CREATE USER myuser WITH PASSWORD 'password';\"" \
&& su postgres bash -c "psql -c \"CREATE DATABASE db WITH OWNER = myuser;\""```
请注意,我甚至尝试在psql命令之前启动 postgresql 服务。
我尝试了另一种方法,即使用基本映像postgres:9.6.3
并在其上安装Python pip。我仍然得到同样的错误。这是第二个Dockerfile供参考:
FROM postgres:9.6.3
WORKDIR /app
ADD . /app
RUN apt-get update && apt-get install -y python-pip libgeos-c1
RUN service postgresql start
RUN su postgres bash -c "psql -c \"CREATE USER myuser WITH PASSWORD 'password';\"" \
&& su postgres bash -c "psql -c \"CREATE DATABASE db WITH OWNER = myuser;\""
忏悔:我是码头工人。
答案 0 :(得分:3)
这与Multiple RUN vs. single chained RUN in Dockerfile, what is better?
相关我也遇到了一个码头工作人员。每个RUN可能不在相同的“上下文”中。请参阅此输出,请注意start命令和psql命令的容器不同。似乎它在构建图像时构建容器的快照。
Step 25/30 : RUN service postgresql start
---> Running in 5c22e985359c
Starting PostgreSQL 9.6 database server: main.
Removing intermediate container 5c22e985359c
---> db1f2c2cdb33
Step 26/30 : USER postgres
---> Running in 6d56501e7286
Removing intermediate container 6d56501e7286
---> b35d3912eacf
Step 27/30 : RUN psql -c "CREATE USER user with password 'password'"
---> Running in 8c9130d2daa5
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain
我使用以下命令将这些命令链接在一起
RUN service postgresql start &&\
sudo -u postgres psql -c "CREATE USER user with password 'password'"
成功创建用户命令的结果,如果需要,应该能够继续进行更多&& \
Step 23/23 : RUN service postgresql start && sudo -u postgres psql -c "CREATE USER user with password 'password'"
---> Running in f234f6074f56
Starting PostgreSQL 9.6 database server: main.
CREATE ROLE
答案 1 :(得分:3)
最好在docker-entrypoint-initdb.d
中使用脚本。
在Dockerfile
COPY ./init-user-db.sh /docker-entrypoint-initdb.d/init-user-db.sh
脚本本身:
#!/bin/bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL
此处有更多详细信息:https://docs.docker.com/samples/library/postgres/#how-to-extend-this-image