docker 容器中 PostgreSQL 的权限问题 [英] Permission issue with PostgreSQL in docker container
问题描述
我正在尝试使用 PostgreSQL 运行一个 docker 镜像,该镜像配置了一个用于持久化数据的卷.
I'm trying to run a docker image with PostgreSQL that has a volume configured for persisting data.
version: '3.1'
services:
db:
image: postgres
restart: always
volumes:
- ./data:/var/lib/postgresql/data
environment:
POSTGRES_PASSWORD: example
当我启动容器时,我看到了输出
When I start the container I see the output
修复现有目录/var/lib/postgresql/data ... 的权限
fixing permissions on existing directory /var/lib/postgresql/data ... ok
并且数据文件夹对我来说不再可读.
and the data folder is no longer readable for me.
如果我提升自己并访问数据目录,我可以看到文件在那里.此外,命令 ls -ld data
给了我
If I elevate myself and access the data directory I can see that the files are there. Furthermore, the command ls -ld data
gives me
drwx------ 19 systemd-coredump root 4096 May 17 16:22 data
我可以使用 sudo chmod 755 data
手动设置目录权限,但这只能在我重新启动容器之前有效.
I can manually set the directory permission with sudo chmod 755 data
, but that only works until I restart the container.
为什么会发生这种情况,我该如何解决?
Why does this happen, and how can I fix it?
推荐答案
另一个答案确实指出了问题的根本原因,但是它指向的帮助页面没有包含解决方案.这是我想出的办法来使这项工作适合我:
The other answer indeed points to the root cause of the problem, however the help page it points to does not contain a solution. Here is what I came up with to make this work for me:
- 使用普通的 docker-compose 文件启动容器,这将使用硬编码的 uid:gid (999:999) 创建目录
version: '3.7'
services:
db:
image: postgres
container_name: postgres
volumes:
- ./data:/var/lib/postgresql/data
environment:
POSTGRES_USER: fake_database_user
POSTGRES_PASSWORD: fake_database_PASSWORD
- 停止容器并手动将所有权更改为您想要的 uid:gid(在此示例中我将使用 1000:1000
$ docker stop postgres
$ sudo chown -R 1000:1000 ./data
- 编辑您的 docker 文件以添加所需的 uid:gid 并使用 docker-compose 再次启动它(注意
user:
)
version: '3.7'
services:
db:
image: postgres
container_name: postgres
volumes:
- ./data:/var/lib/postgresql/data
user: 1000:1000
environment:
POSTGRES_USER: fake_database_user
POSTGRES_PASSWORD: fake_database_password
您不能从一开始就使用 user:
的原因是,如果图像以不同的用户身份运行,则无法创建数据文件.
The reason you can't just use user:
from the start is that if the image runs as a different user it fails to create the data files.
在图像文档页面上,确实提到了添加卷以公开当提供 --user
选项时,/etc/passwd
文件在图像中作为只读文件,但是,这对我使用最新的图像不起作用,因为我得到了以下错误.事实上,提出的三个解决方案都不适合我.
On the image documentation page, it does mention a solution to add a volume to expose the /etc/passwd
file as read-only in the image when providing --user
option, however, that did not work for me with the latest image, as I was getting the following error. In fact none of the three proposed solutions worked for me.
initdb: error: could not change permissions of directory "/var/lib/postgresql/data": Operation not permitted
这篇关于docker 容器中 PostgreSQL 的权限问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!