Coder_Nick
Coder_Nick

Reputation: 841

Rails assets not being loaded on Docker

I have a rails app using Postgres, Puma, Nginx in a Docker environment. Once I run docker-compose build and docker-compose up, I am able to visit the page except the assets (js, images, css) can't be found. I have sign in capability but when I successfully sign in, I get redirected to localhost and not localhost/admin/settings. I have a feeling it is an Nginx configuration problem but so far haven't been able to make any headway.

My nginx.conf is:

server {
  listen       80;

# Allow nginx to serve assets from docker
  location ^~ /my-app/assets/ {
    rewrite /my-app(/assets/.*) $1;
    root /public/;
    gzip_static on;
    expires max;
    add_header Cache-Control public;
    add_header Strict-Transport-Security "";
  }

# Allow nginx to serve assets from ALB
  location ^~ /assets/ {
    root /public/;
    gzip_static on;
    expires max;
    add_header Cache-Control public;
    add_header Strict-Transport-Security "";
  }

  location / {
    proxy_pass http://my-app:3000;
    add_header Strict-Transport-Security "";
  }
}

My docker-compose.yml is:

version: "3.4"
services:
  my-app:
    build:
      context: .
      target: my-app
    restart: "no"
    env_file:
      ./.my-app.env
    links:
      - postgres
    command: >
      /bin/bash -c "
        while ! nc -z postgres 5432;
        do
          echo waiting for postgres;
          sleep 1;
        done;
        echo Connected!;
        bundle exec rake db:create db:migrate;
        rm -f /app/tmp/pids/server.pid
        bundle exec rake assets:clobber
        bundle exec rake assets:precompile RAILS_ENV=production
        bundle exec rake assets:precompile RAILS_ENV=staging
        bundle exec rails server;
     "
  postgres:
    image: postgres:9.6
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
    ports:
      - '5432:5432'
my-app-nginx:
  build:
    context: .
    target: nginx
  links:
    - skymap
  restart: "no"
  ports:
    - '3000:80'

In my Dockerfile, I'm running the Nginx instructions below:

# Start NGINX container config
FROM nginx as nginx
WORKDIR /public
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
COPY public /public

I'm not sure if I'm not setting the path properly or the assets just haven't compiled.

Upvotes: 2

Views: 2773

Answers (1)

Eric Nordelo Galiano
Eric Nordelo Galiano

Reputation: 455

If is not a problem, you can configurate rails to serve static files instead nginx and it will work.

config.serve_static_assets = true

Upvotes: 1

Related Questions