*args **kwargs

Web Development Odds & Ends

Nginx as Jenkins Reverse Proxy

So the previous post was about setting up jenkins to run in a docker container as a debian system service, and the steps outlined there should get you to the point of having a new Jenkins instance running on port 8080. The next step then is to set up nginx as a reverse proxy for the Jenkins server - ie. requests are directed to nginx on port 80 before being passed on to Jenkins.

nginx config

Next install nginx:

- name: Install nginx
  apt: name=nginx

Remove the default server config:

- name: Remove default nginx site (unlink from /etc/nginx/sites-enabled)
  file: path=/etc/nginx/sites-enabled/default state=absent

And create the jenkins proxy config:

  server {
    listen          80;

    # Using a wildcard server_name which will match any incoming request.
    # This should ultimately be set to be the expected host, eg. server_name jenkins.mydomain.com;
    server_name     _;

    root            /var/www/jenkins/;

    access_log      /var/log/nginx/jenkins/access.log;
    error_log       /var/log/nginx/jenkins/error.log;

    location ~ "^/static/[0-9a-fA-F]{8}\/(.*)$" {

          # Rewrite all static files into requests to the site root
          # E.g /static/12345678/css/something.css will become /css/something.css
          rewrite "^/static/[0-9a-fA-F]{8}\/(.*)" /$1 last;

    location @jenkins {
        sendfile off;
        proxy_redirect     default;

        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_max_temp_file_size 0;

        #this is the maximum upload size
        client_max_body_size       10m;
        client_body_buffer_size    128k;

        proxy_connect_timeout      90;
        proxy_send_timeout         90;
        proxy_read_timeout         90;

        proxy_buffer_size          4k;
        proxy_buffers              4 32k;
        proxy_busy_buffers_size    64k;
        proxy_temp_file_write_size 64k;

  location / {

      # If the request uri matches a static file then serve it directly,
      # otherwise pass the request on to jenkins.

      try_files $uri @jenkins;


Copy this config to /etc/nginx/sites-available and create a symlink in /etc/nginx/sites-enabled:

- name: Copy the jenkins nginx reverse proxy config to /etc/nginx/sites-available
  copy: src=files/nginx.conf dest=/etc/nginx/sites-available/jenkins

- name: Link /etc/nginx/sites-available/jenkins to /etc/nginx/sites-enabled
  file: src=/etc/nginx/sites-available/jenkins dest=/etc/nginx/sites-enabled/jenkins state=link

Reload nginx:

- name: Reload nginx
  shell: systemctl restart nginx

Now browse to the server host to complete the initial jenkins configuration and install plugins etc.