首页 > 解决方案 > Getting Forbidden 403 error with nginx docker container when serving static files

问题描述

I am trying to run my angular-cli project with nginx docker container in development mode. Here is the complete boilerplate code.

To avoid every time rebuilding the complete docker image whenever the source code is changed, I am using volumes in my docker compose file and mapping my dist/{project-name} path with container's usr/share/nginx/html path, and then finally running the Angular project in host machine with ng build --watch

But using volumes seems to be causing file read issues to the nginx and it is unable to read index.html

dev.dockerfile:

FROM nginx:alpine
LABEL author="Saurabh Palatkar"
COPY nginx.conf /etc/nginx/nginx.conf

COPY /dist/ng-docker /usr/share/nginx/html
RUN ls /usr/share/nginx/html
RUN ps aux | grep nginx
RUN chown -R root:root /usr/share/nginx/html/index.html
RUN chmod -R 755 /usr/share/nginx/html
RUN ls -al /usr
RUN chmod o+x /usr
RUN chmod o+x /usr/share
RUN chmod o+x /usr/share/nginx
RUN chmod o+x /usr/share/nginx/html
# RUN ls /usr/share/nginx/html
# RUN ls /etc/nginx
EXPOSE 80 443
CMD [ "nginx", "-g", "daemon off;" ]

docker-compose.dev.yml:

version: "2.0"

services:

      angular-nginx-docker:
        image: ng-docker-dev
        build: 
          context: .
          dockerfile: .docker/dev.dockerfile
        environment:
          NODE_ENV: development
        volumes: 
          - "/dist/ng-docker:/usr/share/nginx/html"
        ports:
          - 8080:80
        command: [nginx-debug, '-g', 'daemon off;']

However, I am able to serve my Angular static files through nginx docker container in prod mode (The only difference I see is, I am not using volumes) docker-compose.yml:

version: "2.0"

services:
  angular-nginx-docker:
    image: ng-docker-prod
    build: 
      context: .
      dockerfile: .docker/prod.dockerfile
    environment:
      NODE_ENV: production
    ports:
      - 80:80
      - 443:443
      - 9229:9229
    command: [nginx, '-g', 'daemon off;'] 

prod.dockerfile:

FROM node:latest as angular-built
WORKDIR /usr/src/app
RUN npm i -g @angular/cli
COPY package.json package.json
COPY package-lock.json package-lock.json
RUN npm install --silent
COPY . .
RUN ng build --prod --build-optimizer

FROM nginx:alpine
LABEL author="Saurabh Palatkar"
COPY nginx.conf /etc/nginx/nginx.conf

COPY --from=angular-built /usr/src/app/dist/ng-docker /usr/share/nginx/html

EXPOSE 80 443
CMD [ "nginx", "-g", "daemon off;" ]

标签: angulardockernginxdocker-composeangular-cli

解决方案


使用volumes时,docker会使用宿主系统文件权限模式。我怀疑,您主机上的静态文件(您映射的)没有root读取的权限。

在 dockerfile 中执行chmod不会执行任何操作,因为在构建期间文件不在其中(卷在容器运行时映射)。

我建议chmod -R o+rx /dist/ng-docker在主机上运行,​​以便每个用户(包括 root 用户)都可以阅读它们。如果您不希望这样做,请尝试专门为 root (uid: 0) 设置 ACL,或修改容器以拥有一个用户,该用户将运行 nginx,与uid您一样guid


推荐阅读