Popular blog tags

How To install PostgreSQL On Linux Using Docker

Published

 

postgres Docker Official Image:https://hub.docker.com/_/postgres

postgres Docker Official Image tag:https://hub.docker.com/_/postgres/tags

su userxx

1.Pull the PostgreSQL Docker Image 

docker pull postgres
docker pull postgres:17

 

2. Create a Docker Volume for Data Persistence

docker volume create postgres_data

or

3.Run the PostgreSQL Docker Container 

在宿主机上创建文件夹,其中区分数据和配置。

以普通用户身份创建

mkdir -p  /datadocker/postgres

1.如果用 sudo mkdir 创建文件夹,该文件夹的归属权会变成 root。这可能导致 Docker 容器内的 postgres 用户(UID 通常是 999)无法在里面写入数据,报错“Permission denied”。

2.

# 以普通用户身份创建

mkdir -p ~/postgres_data/data

3.如果已经用 root 创建,可以改回权限:

sudo chown -R $USER:$USER ~/postgres_data

 

 

docker run -d \
  --name postgres \
  -e POSTGRES_PASSWORD='p@ssword$123!'\
  -p 5432:5432 \
  -v /datadocker/postgres/data:/var/lib/postgresql/data \
  -v /datadocker/postgres/config:/etc/postgresql \
  postgres:17

-e POSTGRES_PASSWORD: 设置数据库超级用户的密码(必填)。

-v [宿主机路径]:[容器内路径]: 你刚才创建的文件夹映射到容器内存放数据库文件的地方。

 

 

-e POSTGRES_PASSWORD=mysecretpassword: Sets the required password for the default postgres user.

-v postgres_data:/var/lib/postgresql/data: Mounts the postgres_data volume you created to the directory where PostgreSQL stores its data inside the container.

 

HTTP server listening on http://0.0.0.0:8080/
 
这是容器内部监听地址。

真正决定外部访问的是:

 
-p 127.0.0.1:8090:8080

 

 

Access PostgreSQL with a client

docker exec -it my_postgres psql -U postgres

output

psql (17.7 (Debian 17.7-3.pgdg13+1))
Type "help" for help.

postgres=# ls -l

 

test PostgreSQL from the command line (CLI)

(on the same machine)

telnet <your-vps-tailscale-ip> 5432

From your Windows 10 PC (via Tailscale):

step 1.Install PostgreSQL client tools https://www.postgresql.org/download/windows/

step 2.Open Command Prompt or PowerShell:

psql -h <your-vps-tailscale-ip> -p 5432 -U postgres -d postgres

 

Deleting the volume

docker volume rm my_pgdata