我正在使用 docker 文件构建 ubuntu 镜像,已经安装了 postgresql。但我等不及服务 postgres 状态 OK
FROM ubuntu:18.04
....
RUN apt-get update && apt-get install -y postgresql-11
RUN service postgresql start
RUN su postgres
RUN psql
RUN CREATE USER kong; CREATE DATABASE kong OWNER kong;
RUN \q
RUN exit
一切似乎都很好,但是 RUN su postgres
会抛出错误,因为在 RUN service postgresql start
之后 service postgresql 还没有启动。我该怎么做?
最佳答案
首先,Dockerfile 中的每个 RUN 命令都在单独的 shell 中运行,RUN
命令应该用于安装或配置,而不是用于启动
进程。该过程应从 CMD
或 entrypoint
开始。
最好用官方的postgress docker image .
docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres
默认的 postgres 用户和数据库是在带有 initdb 的入口点创建的。 或者你可以基于 postgress 构建你的图像。
FROM postgres:11
ENV POSTGRES_USER=kong
ENV POSTGRES_PASSWORD=example
COPY seed.sql /docker-entrypoint-initdb.d/seed.sql
这将创建一个包含用户名和密码的图像,并且入口点也会在容器启动时插入种子数据。
POSTGRES_USER
This optional environment variable is used in conjunction with POSTGRES_PASSWORD to set a user and its password. This variable will create the specified user with superuser power and a database with the same name. If it is not specified, then the default user of postgres will be used.
官方 docker 镜像的一些优势
- 从 ENV 创建数据库
- 从 ENV 创建数据库用户
- 启动带有种子数据的容器
- 将等待 postgres 启动并运行
所有你需要的
# Use postgres/example user/password credentials
version: '3.1'
services:
db:
image: postgres
restart: always
environment:
POSTGRES_PASSWORD: example
初始化脚本
If you would like to do additional initialization in an image derived from this one, add one or more
*.sql, *.sql.gz, or *.sh
scripts under/docker-entrypoint-initdb.d
(creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any*.sql
files, run any executable *.sh scripts, and source any non-executable*.sh
scripts found in that directory to do further initialization before starting the service.
关于postgresql - 等待服务 postgres 启动 dockerfile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58722896/