如何在两个 docker 容器之间共享 Docker Volume?

时间:2021-07-02 09:19:08

标签: docker docker-compose

我有以下问题:我有两个 Docker 容器,一个用于我的应用程序,一个用于 NGINX。现在我想与 NGINX 容器共享从我的应用程序上传的图像。我尝试使用卷来做到这一点。但是当我重新启动我的应用程序容器时,图像丢失了。即使在我重新启动或重新创建容器后,如何保存图像?

我的配置: docker-compose.yml

version: '3'

services:
  # the application
  app:
    build:
      context: .
      dockerfile: ./docker/app/Dockerfile
    environment:
      - DB_USERNAME=postgres
      - DB_PASSWORD=postgres
      - DB_PORT=5432
    volumes:
      - .:/app
      - gallery:/app/public/gallery
    ports:
      - 3000:3000
    depends_on:
      - db
  # the database
  db:
    image: postgres:11.5
    volumes:
      - postgres_data:/var/lib/postgresql/data

  # the nginx server
  web:
    build:
      context: .
      dockerfile: ./docker/web/Dockerfile
    volumes:
      - gallery:/app/public/gallery
    depends_on:
      - app
    ports:
      - 80:80

networks:
  default:
    external:
      name: app-network

volumes:
  gallery:
  postgres_data:

app/Dockerfile

FROM ruby:2.7.3

RUN apt-get update -qq
RUN apt-get install -y make autoconf libtool make gcc perl gettext gperf && git clone https://github.com/FreeTDS/freetds.git && cd freetds && sh ./autogen.sh && make && make install

# for imagemagick
RUN apt-get install imagemagick

# for postgres
RUN apt-get install -y libpq-dev

# for nokogiri
RUN apt-get install -y libxml2-dev libxslt1-dev

# for a JS runtime
RUN apt-get install -y nodejs

# Setting an Envioronment-Variable for the Rails App
ENV RAILS_ROOT /var/www/app
RUN mkdir -p $RAILS_ROOT

# Setting the working directory
WORKDIR $RAILS_ROOT

# Setting up the Environment
ENV RAILS_ENV='production'
ENV RACK_ENV='production'

# Adding the Gems
COPY Gemfile Gemfile
COPY Gemfile.lock Gemfile.lock
RUN bundle install --jobs 20 --retry 5 --without development test

# Adding all Project files
COPY . .
RUN bundle exec rake assets:clobber
RUN bundle exec rake assets:precompile

EXPOSE 3000
CMD ["bundle", "exec", "puma", "-p", "3000"]

web/Dockerfile

# Base Image
FROM nginx

# Dependiencies
RUN apt-get update -qq && apt-get -y install apache2-utils

# Establish where Nginx should look for files
ENV RAILS_ROOT /var/www/app

# Working Directory
WORKDIR $RAILS_ROOT

# Creating the Log-Directory
RUN mkdir log

# Copy static assets
COPY public public/

# Copy the NGINX Config-Template
COPY docker/web/nginx.conf /tmp/docker.nginx

# substitute variable references in the Nginx config template for real values from the environment
# put the final config in its place
RUN envsubst '$RAILS_ROOT' < /tmp/docker.nginx > /etc/nginx/conf.d/default.conf

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

1 个答案:

答案 0 :(得分:1)

您可以将主机上的同一目录同时挂载到多个 Docker 容器,而不是卷。只要容器没有同时写入同一个文件(这不在您描述的用例中),您就不应该有问题。

例如:

docker run -d  --name Web1 -v /home/ubuntu/images:/var/www/images httpd
docker run -d  --name Other1 -v /home/ubuntu/images:/etc/app/images my-docker-image:latest

如果您更喜欢 Docker 卷,this article 将为您提供您需要知道的一切。