Docker for Postgresql数据库与数据导入

vvppvyoh  于 2024-01-06  发布在  Docker
关注(0)|答案(2)|浏览(181)

我正在尝试为PostgreSQL数据库创建一个Docker,并导入一些数据到其中。我已经遵循了官方文档。
Dockerfile看起来像这样:

  1. FROM postgres:14.10
  2. #Set env vars
  3. ENV PGDATA=/var/pgdata
  4. ENV POSTGRES_USER=postgres
  5. ENV POSTGRES_PASSWORD=admin
  6. ENV POSTGRES_HOST_AUTH_METHOD=trust
  7. # Copy backup to container
  8. COPY opr.dump /opr.dump
  9. COPY entrypoint2.sh /docker-entrypoint-initdb.d/entrypoint2.sh
  10. ENTRYPOINT ["docker-entrypoint.sh"]
  11. CMD ["postgres"]

字符串
入口点脚本看起来像这样:

  1. #!/bin/bash
  2. set -e
  3. # Create the Postgres database
  4. createdb opr
  5. # Extract the schema and data from the backup file
  6. pg_restore -U postgres -d opr /opr.dump


一切正常,但导入数据后,容器停止,无论是在附加和分离模式。我复制了从官方形象的入口点和CMD,但没有成功。
我应该提到的是,我也尝试过不复制ENTRYPOINT和CMD,容器仍然停止。
我的问题是如何让容器在导入数据后不停止?

mwyxok5s

mwyxok5s1#

您只需要将entrypoint2.sh脚本复制到docker-entrypoint-initdb.d目录中,就像the documentation一样(请参阅脚本一节)
如果您想在从此映像派生的映像中执行其他初始化,请在/docker-entrypoint-initdb.d [...]下添加一个或多个 .sql、.sql.gz或 *.sh脚本,它将运行任何可执行的 *.sh脚本,并获取该目录中找到的任何不可执行的 *.sh脚本,以便在启动服务之前执行进一步的初始化。
因此,无需覆盖ENTRYPOINTCMD
编辑:看起来你将不得不这样做后,容器开始,就像大卫迷宫指出。

wwtsj6pe

wwtsj6pe2#

最后,我成功地创建了一个自定义的入口点脚本来完成这个任务。
Dockerfile看起来像这样:

  1. FROM postgres:14.10
  2. #Set env vars
  3. ENV PGDATA=/var/pgdata
  4. ENV POSTGRES_USER=postgres
  5. ENV POSTGRES_PASSWORD=admin
  6. ENV POSTGRES_HOST_AUTH_METHOD=trust
  7. # Create a directory to store PostgreSQL data and logs
  8. RUN mkdir -p ${PGDATA} /tmp /var/log/postgresql && chown -R postgres:postgres ${PGDATA} /tmp /var/log/postgresql
  9. WORKDIR /data
  10. # Expose the PostgreSQL port
  11. EXPOSE 5432
  12. # Copy the entrypoint script to the container
  13. COPY entrypoint.sh /entrypoint.sh
  14. RUN chmod +x /entrypoint.sh
  15. # Copy backup to container
  16. COPY opr.dump /opr.dump
  17. # Set the user to run the container
  18. USER postgres
  19. # Run the entrypoint script
  20. CMD ["/entrypoint.sh"]

字符串
入口点脚本看起来像这样:

  1. #!/bin/bash
  2. # Initialize the PostgreSQL data directory
  3. initdb -D ${PGDATA}
  4. #change hba_conf
  5. echo "host all all all trust" >> /var/pgdata/pg_hba.conf
  6. # Start PostgreSQL in the background
  7. pg_ctl -D ${PGDATA} -l /var/log/postgresql/logfile start
  8. # Wait for PostgreSQL to start
  9. wait_postgresql() {
  10. while ! pg_isready -q; do
  11. echo "Waiting for PostgreSQL to start..."
  12. sleep 1
  13. done
  14. }
  15. wait_postgresql
  16. # Create the Postgres database
  17. createdb opr
  18. # Extract the schema and data from the backup file
  19. pg_restore -U postgres -d opr /opr.dump
  20. # Keep PostgreSQL running
  21. tail -f /var/log/postgresql/logfile

展开查看全部

相关问题