Ephemeral shared volume in docker

Viewed 1001

I'm looking for a way to share an arbitrary directory in one Docker container with another, but without persisting the volumes between container creations.

The use case is sharing static assets between a web application and a web server like nginx. Both containers are built by an image. The web application's Dockerfile copies the static assets to a directory like /var/www/public when it's built. I want to avoid persisting the volume because the static assets are updated when the web application is built.

I've attempted this with a docker-compose.yml that looks like the following, but unfortunately this persists the volume and when a container is recreated with the new image, the contents of the shared volume aren't updated.

version: '3.5'

services:
  web:
    image: bswinnerton/nyc-restaurant-grades
    networks:
      - backend
    volumes:
      - www_data:/var/www/app/
  nginx:
    image: nginx
    depends_on:
      - web
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - www_data:/var/www/app/
    networks:
      - backend

volumes:
  www_data:

networks:
  backend:

And the web application's Dockerfile looks something like this:

FROM ruby:2.5.1

# Install dependencies
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs

# Set working directory, where the commands will be ran:
RUN mkdir -p /var/www/app
WORKDIR /var/www/app

# Adding gems
COPY Gemfile Gemfile
COPY Gemfile.lock Gemfile.lock
RUN bundle install --jobs 20 --retry 5

# Adding project files
COPY . .

# Precompile assets
RUN bundle exec rails assets:precompile

CMD [ "bundle", "exec", "puma", "-C", "config/puma.rb" ]

I considered using a tmpfs mount, but it appears they cannot be shared between containers.

1 Answers

If you’re looking to do this in a Docker/Compose environment, I’d probably just use a folder on disk and configure it upon startup of the containers. Another alternative is to have your build pipeline copy the files out of one image and into another using docker cp to the build environment and COPY in the subsequent Dockerfile (assuming they're static files).

If you’re looking to do this in Kubernetes, this is achievable with emptyDir volumes and pods with multiple containers (sidecars).

Related