如何在 Docker Compose 中设置 uid 和 gid?

ing*_*ere 33 bash shell docker docker-compose

我可以这样执行docker run命令......

docker run --rm  --user $(id -u):$(id -g) -e MYDATA=/some/path/to/data -e USER=$USER -p 8883-8887:8883-8887 ...
Run Code Online (Sandbox Code Playgroud)

但是,在 Docker Compose 中,当我写出以下内容时......

version: '3.7'
services:
  container_name: some-server
  image: some:img
  user: $(id -u):$(id -g) 
  ... 
Run Code Online (Sandbox Code Playgroud)

... 这是行不通的。

我知道我要求docker-compose up执行子 shell 命令替换,但它不能。

有没有办法做到这一点?

Edw*_*ung 46

试试这个

所以,你需要把:

user: "${UID}:${GID}"
Run Code Online (Sandbox Code Playgroud)

在您的 docker compose 中并提供 UID 和 GID 作为 docker-compose 参数

UID=${UID} GID=${GID} docker-compose up
Run Code Online (Sandbox Code Playgroud)

(或将 UID 和 GID 定义为环境变量)。

  • 也许更有效:`UID =“$(id -u)”GID =“$(id -g)”docker-compose up`或者,`UID_GID =“$(id -u):$(id -g)” docker-compose up`(并且在 compose 集内`user: "${UID_GID}"` ... (12认同)
  • `$ UID=xxx cmd` 对于所有 shell 来说并不是一个好主意,因为(例如)在 bash 中 UID 是一个只读变量并且已经存在,但未导出。@ingyhere 的评论确实是正确的选择。 (8认同)
  • 为什么需要将 UID 和 GID 显式设置为它们已有的值?为什么仅仅“docker-compose up”还不够?编辑:找到答案;它们是 shell 变量而不是环境变量。https://github.com/docker/compose/issues/4725 (4认同)
  • 对我来说,当我使用不带引号的 docker-compose 文件时,它会起作用:“user: ${UID_GID}”。我正在使用 docker-compose `版本:'3.8'` (2认同)

Ami*_*esh 17

这也可以做到

在你的 docker-composer.yml 中

user: $DOCKER_USER
Run Code Online (Sandbox Code Playgroud)

在命令行中

echo 'export DOCKER_USER="$(id -u):$(id -g)"' >> ~/.bash_profile

source ~/.bash_profile

docker-compose up
Run Code Online (Sandbox Code Playgroud)

创建一个 DOCKER_USER 变量并将其添加到 bash_profile 中以实现持久性。该源代码将帮助 shell 按需识别 .bash_profile 的更改