如何在Postgres Dockerfile中正确设置VOLUME和CMD指令?
我有一个工作的Postgres Dockerfile,我修改后,不幸的是应用修改Postgres容器停止按预期工作。 我想问你解释我做错了什么。
工作示例
这是Postgres Dockerfile,它可以工作,也可以修改:
# Use ubuntu image FROM ubuntu # Install database RUN apt-get update && apt-get install -y postgresql-9.3 # Switch to postgres user. USER postgres # Create databse and user with all privileges to the database. RUN /etc/init.d/postgresql start && \ psql --command "CREATE DATABASE docker;" && \ psql --command "CREATE USER docker WITH SUPERUSER PASSWORD 'docker';" &&\ psql --command "GRANT ALL PRIVILEGES ON DATABASE docker TO docker;" # Allow remote connections to the database. RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/9.3/main/pg_hba.conf RUN echo "listen_addresses='*'" >> /etc/postgresql/9.3/main/postgresql.conf # Add VOLUMEs to allow backup of config, logs and databases VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"] # Set the default command to run when starting the container CMD ["/usr/lib/postgresql/9.3/bin/postgres", "-D", "/var/lib/postgresql/9.3/main", "-c", "config_file=/etc/postgresql/9.3/main/postgresql.conf"]
我这样构build:
docker build --tag postgres-image .
然后我创build一个容器:
docker run -d -it -p 32768:5432 --name=postgres postgres-image
我连接数据库:
psql -h localhost -p 32768 -d docker -U docker --password
第一次修改
我不需要任何卷,因为我打算使用将存储所有Postgres数据的仅数据容器。 当我删除该行时:
VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
并在工作示例中执行所有步骤后,在最后一步传递密码后出现以下错误:
psql: FATAL: the database system is starting up FATAL: the database system is starting up
所以问题是: 为什么我需要Dockerfile中的VOLUME指令?
第二个修改
这个修改不包括第一个。 两个修改都是独立的。
在CMD instraction中使用的参数指向默认的Postgres数据目录和configuration文件,所以我想通过将CMD设置为我始终用来启动Posgres的命令来简化它:
service postgres start
将CMD设置为:
CMD ["service", "postgres", "start]
并像在工作示例中一样执行所有步骤,在最后一步传递密码后出现以下错误:
psql: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 32768?
问题是: 为什么在我的主机系统上运行的命令在Docker容器中不起作用?
我不确定第一个问题。 Postgres 可能不喜欢在UFS之上运行。
第二个问题就是容器在主进程结束时会退出。 所以命令“服务postgres开始”运行,在后台启动Postgres然后立即退出和容器停止。 第一个版本工作,因为Postgres保持在前台运行。
但是你为什么这样做呢? 为什么不使用官方Postgres图像 ?