Docker - Can't share data between containers within a volume (docker-compose 3)

后端 未结 2 650
既然无缘
既然无缘 2021-02-07 20:15

I have some containers for a web app for now (nginx, gunicorn, postgres and node to build static files from source and a React server side rendering). In a Dockerfile for the no

2条回答
  •  旧巷少年郎
    2021-02-07 20:37

    Explanation of what happens step by step

    Dockerfile.node

        ...
        COPY ./client /usr/src
        ...
    

    docker-compose.yml

    services:
      ...
      node:
        ...
        volumes:
          - ./server/nginx.conf:/etc/nginx/nginx.conf:ro
          - vnode:/usr/src
      ...
    volumes:
      vnode:
    
    1. docker-compose up creates with this Dockerfile.node and docker-compose section a named volume with data saved in /usr/src.

    Dockerfile.nginx

    FROM nginx:latest
    
    COPY ./server/nginx.conf /etc/nginx/nginx.conf
    
    RUN mkdir -p /var/www/tg/static
    
    EXPOSE 80
    EXPOSE 443
    
    CMD ["nginx", "-g", "daemon off;"]
    
    1. That produces that nginx containers created with docker-compose will have an empty /var/www/tg/static/

    docker-compose.yml

     ...
     nginx:
        build:
          context: .
          dockerfile: ./Dockerfile.nginx
        container_name: tg_nginx
        restart: always
        volumes:
          - ./server/nginx.conf:/etc/nginx/nginx.conf:ro
          - vnode:/var/www/tg/static
        ports:
          - "80:80"
          - "443:443"
        depends_on:
          - node
          - gunicorn
        networks:
          - nw_web_tg
    
     volumes:
       vdata:
       vnode:
    
    1. docker-compose up will produce that vnode named volume is created and filled with data from /var/www/tg/static (empty by now) to existing vnode.

    So, at this point, - nginx container has /var/www/tg/static empty because it was created empty (see mkdir in Dockerfile.nginx) - node container has /usr/src dir with client file (see that was copied in Dockerfile.node) - vnode has content of /usr/src from node and /var/www/tg/static from nginx.

    Definitively, to pass data from /usr/src from your node container to /var/www/tg/static in nginx container you need to do something that is not very pretty because Docker hasn't developed another way yet: You need to combine named volume in source folder with bind volume in destination:

     nginx:
         build:
           context: .
           dockerfile: ./Dockerfile.nginx
         container_name: tg_nginx
         restart: always
         volumes:
           - ./server/nginx.conf:/etc/nginx/nginx.conf:ro
           - /var/lib/docker/volumes/vnode/_data:/var/www/tg/static
         ports:
           - "80:80"
           - "443:443"
         depends_on:
           - node
           - gunicorn
         networks:
           - nw_web_tg
    

    Just change in docker-compose - vnode:/var/www/tg/static by - /var/lib/docker/volumes/vnode/_data:/var/www/tg/static

提交回复
热议问题