首页 > 解决方案 > 将主机映射到容器以在源代码更改时进行即时更新时出现 Docker 权限问题

问题描述

我在玩 docker,似乎遇到了这个权限问题。我从样板反应应用程序开始,并尝试将源代码(在我的计算机上,即主机上)的更改映射到我的容器上,以便我立即看到更新。所以我不必一次又一次地构建我的图像和创建容器。如果我真的从头开始构建所有东西,那么一切都很好,没有权限问题。

这是我的码头文件

FROM node:14.17.5-alpine3.14
RUN addgroup app && adduser -S -G app app 
# creating folders first to avoid permission issues
RUN mkdir /app
# directory to map a volume
RUN mkdir /app/data
# changing folder permissions
RUN chown -R app:app /app
# Set app as user AFTER setting permissions
USER app
WORKDIR /app
# Copy and install separtely to speed up builds
COPY --chown=app:app package*.json yarn.lock ./ 
RUN yarn install
# Copy (& also give owner rights to the current user probably unnecessary)
COPY --chown=app:app . .
# the env var is unnecessary, just for testing
ENV API_URL=http://api.myapp.com/
EXPOSE 3000
CMD ["yarn", "start"]

然后我构建我的图像并创建我的容器,如下所示,它按预期工作。用户app是所有者并具有正确的权限。当我访问 localhost:5002 时,一切都很好

# create container but I don't map host to container
docker run -d -p 5002:3000 --name not-mapped-container dockerized-react-app
# run interactive shell
sudo docker exec -it <container_id/name> sh
# from inside container's shell I list the files
# and everything is what I expect
/app $ ls -l
total 528
-rw-rw-r--    1 app      app            664 Aug 20 15:45 Dockerfile
-rw-r--r--    1 app      app           3362 Aug 19 19:14 README.md
drwxr-xr-x    1 app      app           4096 Aug 20 15:45 data
drwxr-xr-x    1 app      app           4096 Aug 20 17:27 node_modules
-rw-rw-r--    1 app      app            824 Aug 19 19:14 package.json
drwxrwxr-x    2 app      app           4096 Aug 19 19:14 public
drwxrwxr-x    2 app      app           4096 Aug 19 19:14 src
-rw-rw-r--    1 app      app         510089 Aug 19 19:14 yarn.lock

但是现在如果我做几乎完全相同的事情,但尝试将主机映射到容器。事情并不像预期的那样,目录的所有者是用户node而不是app(根据我的 dockerfile 设置的用户)。现在当我去 localhost:8080 时,我得到以下权限问题EACCES: permission denied, mkdir '/app/node_modules/.cache'

# The only change, trying to map host with containers for instant updates
docker run -d -p 8080:3000 --name mapped-container -v $(pwd):/app  dockerized-react-app
# run interactive shell again
sudo docker exec -it <container_id/name> sh
# list the files again but now the owner is node
/app $ ls -l
total 556
-rw-rw-r--    1 node     node           664 Aug 20 15:45 Dockerfile
-rw-r--r--    1 node     node          3362 Aug 19 19:14 README.md
drwxrwxr-x 1047 node     node         36864 Aug 19 19:14 node_modules
-rw-rw-r--    1 node     node           824 Aug 19 19:14 package.json
drwxrwxr-x    2 node     node          4096 Aug 19 19:14 public
drwxrwxr-x    2 node     node          4096 Aug 19 19:14 src
-rw-rw-r--    1 node     node        510089 Aug 19 19:14 yarn.lock

那么为什么会这样呢?我没有正确地将主机上的源代码映射到容器还是别的什么?

标签: reactjsdockerdockerfile

解决方案


推荐阅读