【问题标题】:How to properly set VOLUME and CMD instructions in Postgres Dockerfile?如何在 Postgres Dockerfile 中正确设置 VOLUME 和 CMD 指令?
【发布时间】:2015-06-12 14:50:38
【问题描述】:

我有一个正在修改的 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"]

我是这样构建的:

docker build --tag postgres-image .

然后我创建一个容器:

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 中使用的参数指向默认的 Postgres 数据目录和配置文件,所以我想通过将 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 容器中不起作用?

【问题讨论】:

    标签: postgresql docker dockerfile


    【解决方案1】:

    我不确定第一个问题。 可能 Postgres 不喜欢在 UFS 之上运行。

    第二个问题是容器会在其主进程结束时退出。因此命令“service postgres start”运行,在后台启动 Postgres,然后立即退出,容器停止。第一个版本有效,因为 Postgres 一直在前台运行。

    但是你为什么要这样做呢?为什么不直接使用official Postgres image

    【讨论】:

    • 感谢您的回答。我这样做只是为了培训,以便更好地了解事情的运作方式。
    • 好的。我会尝试查看官方图片并弄清楚他们为什么会这样做。
    • 我已经在其他机器上测试了第一次修改,但由于我找不到导致此类错误的 VOLUME 指令的任何理由,因此没有出现我所期望的错误。
    • 我在第一台电脑上又试了一次,没有 VOLUME 指令的 Dockerfile 运行良好。我无法解释是什么导致了所描述的错误。我不会调查它,因为一切正常。感谢您的帮助。
    猜你喜欢
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    相关资源
    最近更新 更多