如何使用Dockerfile创建PostgreSQL数据库

来自:网络
时间:2024-03-31
阅读:
免费资源网 - https://freexyz.cn/

官网下载基本镜像

[root@localhost ~]# docker pull postgres:latest

创建项目目录

[root@localhost ~]# mkdir /root/postgresql

创建一个名为 “Dockerfile” 的文件

[root@localhost ~]# vim Dockerfile
# 使用官方的PostgreSQL镜像
FROM postgres:latest
# 设置环境变量(设置数据库登录密码)
ENV POSTGRES_PASSWORD=aczu102030
# 将当前目录下的init.sql文件复制到容器中的/docker-entrypoint-initdb.d/目录
COPY init.sql /docker-entrypoint-initdb.d/
# 暴露PostgreSQL的默认端口
EXPOSE 5432
# 在容器启动时执行命令
CMD ["postgres"]

创建一个名为init.sql的文件

[root@localhost ~]# vim init.sql
CREATE TABLE mytable (  
  id SERIAL PRIMARY KEY,  
  name VARCHAR(100)  
);  
INSERT INTO mytable (name) VALUES ('John'), ('Jane'), ('Doe');

使用Dockerfile构建

[root@localhost postgres]# docker build -t my-postgres .  

构建一个名为my-postgres的Docker镜像

运行PostgreSQL容器

[root@localhost postgres]# docker run -d --name my-postgres-container -p 5432:5432 my-postgres

后台运行一个名为my-postgres-container的容器,将主机的5432端口映射到容器的5432端口。

允许远程连接到 PostgreSQL 容器

进入PostgreSQL 容器

[root@localhost postgres]# docker exec -it <容器名称或 ID> bash

允许 PostgreSQL 监听所有地址。

root@59fc0bb64dea:/# echo "host all  all    0.0.0.0/0  md5" >> /var/lib/postgresql/data/pg_hba.conf
root@59fc0bb64dea:/# exit

重启PostgreSQL 容器。

[root@localhost postgres]# docker restart 59fc0bb64dea

远程连接时使用正确的用户名、密码和数据库名进行连接。

免费资源网 - https://freexyz.cn/
返回顶部
顶部