docker这东西安装中间件真是方便,不需要再去手动下载安装包,省事,今天分享一下我在docker中安装postgresql数据库的过程。
1.搜索
docker search postgresql
2.上面可以看到NAME为postgres的镜像,直接安装,我选择的是10.5版本
docker pull postgres:10.5
3.经过10分钟左右,镜像下载下来了,查看一下
docker image list
REPOSITORY TAG IMAGE ID CREATED SIZE
haproxy latest 26a3b0a2daac 3 months ago 92.2MB
hello-world latest fce289e99eb9 14 months ago 1.84kB
postgres 10.5 3fce051f5a48 17 months ago 228MB
4.创建数据目录,一会需要将这个目录映射到docker容器中,启动后会将数据与配置文件写入到这个文件中,这个目录删除后会丢失数据
mkdir /home/docker/pg/data
5.启动postgresql容器
docker run --name mypostgres -e POSTGRES_PASSWORD=123456!@# -p 5432:5432 -v /home/docker/pg/data:/var/lib/postgresql/data -d postgres:10.5
-e POSTGRES_PASSWORD设置postgres用户密码
后面的postgres:10.5为REPOSITORY+":"+TAG,也可以用IMAGE ID启动
启动后会自动生成数据文件和配置文件在映射的/home/docker/pg/data文件中,如果需要日志需要修改数据目录下的postgresql.conf配置文件
再分享下我写的启动脚本
启动脚本start.sh:
#!/bin/bash
serName=mypostgres
cIdAndImageId=$(docker ps -a --filter name=$serName --format "{{.ID}}:{{.Image}}")
echo "stop...find ${serName} docker $cIdAndImageId"
echo $cIdAndImageId
containId=
if [ "$cIdAndImageId" = "" ]
then
echo "docker pid not found! docker create a new container and run it..."
docker run --name "$serName" -e POSTGRES_PASSWORD=123456!@# -p 5432:5432 -v /home/docker/pg/data:/var/lib/postgresql/data -d postgres:10.5
else
array=(${cIdAndImageId//:/ })
containId=${array[0]}
echo "find docker containId:"$containId
fi
if [ -n "$containId" ]
then
docker stop "$containId"
docker start "$containId"
echo "start success!"
fi停止脚本stop.sh:
#!/bin/bash
serName=mypostgres
cIdAndImageId=$(docker ps -a --filter name=$serName --format "{{.ID}}:{{.Image}}")
echo "stop...find ${serName} docker $cIdAndImageId"
echo $cIdAndImageId
containId=
if [ "$cIdAndImageId" = "" ]
then
echo "docker pid not found!"
else
array=(${cIdAndImageId//:/ })
containId=${array[0]}
echo "find docker containId:"$containId
fi
if [ -n "$containId" ]
then
docker stop "$containId"
echo "stop success!"
fi重启脚本restart.sh:
#!/bin/bash
workdir=$(cd $(dirname $0); pwd)
sh "$workdir"/stop.sh
sleep 15
sh "$workdir"/start.sh设置一下权限就可以轻松启动postgresql数据了