在Docker中使用nginx提供Rails的预编译资产

jer*_*101 8 ruby-on-rails docker docker-compose

目前我正在使用docker设置我的应用.我有一个最小的rails应用程序,有1个控制器.你可以运行以下命令来获取我的设置:

rails new app --database=sqlite --skip-bundle
cd app
rails generate controller --skip-routes Home index
echo "Rails.application.routes.draw { root 'home#index' }" > config/routes.rb
echo "gem 'foreman'" >> Gemfile
echo "web: rails server -b 0.0.0.0" > Procfile
echo "port: 3000" > .foreman
Run Code Online (Sandbox Code Playgroud)

我有以下设置:

Dockerfile:

FROM ruby:2.3

# Install dependencies
RUN apt-get update && apt-get install -y \
      nodejs \
      sqlite3 \
      --no-install-recommends \
      && rm -rf /var/lib/apt/lists/*

# Configure bundle
RUN bundle config --global frozen 1
RUN bundle config --global jobs 7

# Expose ports and set entrypoint and command
EXPOSE 3000
CMD ["foreman", "start"]

# Install Gemfile in different folder to allow caching
WORKDIR /tmp
COPY ["Gemfile", "Gemfile.lock", "/tmp/"]
RUN bundle install --deployment

# Set environment
ENV RAILS_ENV production
ENV RACK_ENV production

# Add files
ENV APP_DIR /app
RUN mkdir -p $APP_DIR
COPY . $APP_DIR
WORKDIR $APP_DIR

# Compile assets
RUN rails assets:precompile
VOLUME "$APP_DIR/public"
Run Code Online (Sandbox Code Playgroud)

在哪里VOLUME "$APP_DIR/public"创建与Nginx容器共享的卷,其中包含以下内容Dockerfile:

FROM nginx

ADD nginx.conf /etc/nginx/nginx.conf
Run Code Online (Sandbox Code Playgroud)

然后docker-compose.yml:

version: '2'

services:
  web:
    build: config/docker/web
    volumes_from:
      - app
    links:
      - app:app
    ports:
      - 80:80
      - 443:443
  app:
    build: .
    environment:
      SECRET_KEY_BASE: 'af3...ef0'
    ports:
      - 3000:3000
Run Code Online (Sandbox Code Playgroud)

这有效,但只是我第一次构建它.如果我更改任何资产,并再次构建图像​​,它们就不会更新.可能因为图像构建时未更新卷,我认为因为Docker如何处理缓存.

我希望每次运行时都能更新资产docker-compose built && docker-compose up.知道怎么做到这一点?

dne*_*hin 3

Compose 在重新创建时保留卷

您有几个选择:

  1. 不要对资产使用卷,而是在构建期间将资产和ADD/或COPY它们构建到 Web 容器中
  2. docker-compose rm app在运行之前up删除旧的容器和卷。