lxq.link
postscategoriestoolsabout

通过 docker 安装和使用 postgres 数据库

安装

安装方式很简单:

# 获取镜像
docker pull postgres

# 在宿主机创建存放数据的文件夹
mkdir -p /root/sql_data/data

# 运行容器
docker run --name postgres_cont -e POSTGRES_PASSWORD=postgres -p 5432:5432 -v /root/sql_data/data:/var/lib/postgresql/data -d postgres

需要注意的是,docker commit 在镜像内不会保存数据库数据。原因如下:

The problem is that the postgres Dockerfile declares "/var/lib/postgresql/data" as a volume. This is a just a normal directory that lives outside of the Union File System used by images. Volumes live until no containers link to them and they are explicitly deleted.

所以在部署时需要将容器里面存放数据的文件夹,映射到宿主机的文件夹;

存在这样的机制,可以将数据与容器解耦,方便容器更新;


使用

镜像默认创建好一个数据库用户 ==> postgres

# 进入容器
docker exec -it <ID> bash

# 切换到数据库用户
su postgres

# 进入到数据库命令行交互模式
psql

# 查看数据库
\l
2020-05-17