简体   繁体   English

在 docker 容器中创建正在运行的 Postgres 服务

[英]Creating a running Postgres service inside a docker container

I'm a bit new to Docker.我对 Docker 有点陌生。
I have two containers running using docker-compose.我有两个使用 docker-compose 运行的容器。
One is the API and the other is the actual application.一个是API,一个是实际应用。
I want to add a new DB container using the Postgres official image.我想使用 Postgres 官方镜像添加一个新的数据库容器。
It's a bit hard to find a simple tutorial on how to create the container and populate it with a predefined sql file (of schemas and data).很难找到有关如何创建容器并使用预定义的 sql 文件(模式和数据)填充它的简单教程。

When I start with "CMD /etc/init.d/postgresql start" in the Dockerfile I get an error saying: "No PostgreSQL clusters exist; see "man pg_createcluster"... (warning)."当我在 Dockerfile 中使用“CMD /etc/init.d/postgresql start”启动时,我收到一条错误消息:“不存在 PostgreSQL 集群;请参阅“man pg_createcluster”...(警告)。”

Since it takes me too much time to get things going I was wondering if it might be better to get an Ubuntu image and install Postgres on my own since there is only one source on how to use the image - docker hub, and I don't seem to understand it that well.因为我花了太多时间来处理事情,所以我想知道获取一张 Ubuntu 图像并自己安装 Postgres 是否更好,因为关于如何使用该图像只有一个来源 - docker hub,我不知道似乎不太了解。

Any ideas or simple steps on how to compose and 'configure' this image?关于如何合成和“配置”此图像的任何想法或简单步骤?

If you want populate your database with some file, A simply way to do this is: 如果要用某些文件填充数据库,执行此操作的一种简单方法是:

How to extend this image 如何扩展此图像

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). 如果要在从该镜像派生的映像中进行其他初始化,请在/docker-entrypoint-initdb.d下添加一个或多个* .sql,*。sql.gz或* .sh脚本(必要时创建目录) )。 After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files and source any *.sh scripts found in that directory to do further initialization before starting the service. 入口点调用initdb创建默认的postgres用户和数据库后,它将运行任何* .sql文件并提供在该目录中找到的所有* .sh脚本,以在启动服务之前进行进一步的初始化。

Dockerfile Docker文件

FROM postgres:alpine
COPY init.sql /docker-entrypoint-initdb.d/init.sql

docker-compose.yml docker-compose.yml

version: '3'
services:
  app:
  //your app definition
  postgres:
    build: .

Pull the postgres image拉取 postgres 镜像

docker pull postges:14.2

Create the service with the below command使用以下命令创建服务

docker service create --name postgres --network my_overlay --env "POSTGRES_PASSWORD=password" --publish 5432:5432 postgres:14.2

Try to connect using userName as postgres and password as password to the default postgres db.尝试使用用户名作为postgres和密码作为密码连接到默认的postgres数据库。

jdbc:postgresql://127.0.0.1:5432/postgres // JDBC connection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM