nimavat.me

Java, Groovy, Grails, Spring, Vue, Ionic + Fun blog

Grails Asset pipeline - Serve static files with nginx

|

Grails applications are deployed to tomcat or other java webservers. Web servers can serve both static assets as well as dynamic content. This setup works well for low traffic sites, however as traffic increases static assets can waste a lot of web server resources.

Nginx is a small webserver and reverse proxy which can also work as HTTP Cache and is very good at serving static files. Nginx can be configured to serve and cache the static files, and proxy other requests to tomcat.

Grails configuration

I’ll assume that you are using Asset Pipeline grails plugin. First we need to get the static files out of war file and store to a directory from where the Nginx can serve it.

File: /grails-app/conf/Config.groovy or (application.yml/application.groovy) Depending on grails version


environments {
	production {
		grails {
			assets {
				storagePath = "/assets" //directory path where asset pipeline will store all the asset when deployed to tomcat
			}
		}
	}

Now, asset pipeline will copy all asset files to the configured storage path on application startup.

Nginx configuration

File: /etc/nginx/nginx.conf

http {
	.....
	include /etc/nginx/conf.d/*.conf;
}

File: /etc/nginx/conf.d/grails.conf

upstream web {
  server tomcathost:8080; #replace tomcathost with hostname of your machine where tomcat is running
}

server {
    listen 80;
    server_name mydomain.com; #Replace with domain name of your site.
    access_log /var/log/nginx/grails.log;

    gzip on;
    gzip_types      text/html text/css text/js;
    gzip_min_length 1000;
    gunzip on;

    
    location /assets/ {
        alias /assets/; #This directory path must be same as the path configured as storage path in asset pipeline configration above.
    }

    location / {
        proxy_pass http://web;
        proxy_set_header   Host $host;
        proxy_redirect     off;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
       
    }
}

Above configuration defines many important things

  1. upstream block defines the host and port of the origin tomcat server.
  2. server block defines the domain name and other settings for the nginx
  3. The most important, location /assets/ defines that all urls starting with /assets/xxx will be served by nginx and the files will be looked under alias /assets/ which is absolute path to directory containing the static assets
  4. the bottom location block defines that all other requests will be passed to tomcat