Running Jenkins behind Nginx


Background: Nginx can be used as a Reverse Proxy, Load Balancer, and http Cache. In this tutorial, I am going to use its Reverse Proxy capability. A reverse proxy server decides which backend application it should forward the user request to.

So, let’s say, there is an internal server which is running three web applications – A, B, C. And this internal server should not be exposed to the external world. We can run Nginx server that will be exposed to the outer world. And then based on the request, we can add logic Nginx helping it to decide which backend application to call.
So, this way, internal details are blocked from the external view.
Now let’s start with running Jenkins behind Nginx.
To run Nginx, we need a nginx.conf file which will be read by Nginx.

So below is the Nginx.conf file which I have used.



events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen      5000;
       server_name Jenkins.example_server.com;
                    proxy_set_header        Host $host:$server_port;
             proxy_set_header        X-Real-IP $remote_addr;
             proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_set_header        X-Forwarded-Proto $scheme;
            
             location /jenkins {
                   proxy_pass "http://localhost:8085/jenkins";
                   sub_filter "http://localhost:8085/jenkins" "http://localhost:5000/Jenkins";
                   sub_filter_once on;
             }
            
             location / {
                   proxy_pass "http://localhost:8085/jenkins/";
                   sub_filter "http://localhost:8085/jenkins" "http://localhost:5000/Jenkins";
                   sub_filter_once on;
             }

}



Let me explain the important keywords here.
Location tag will identify the context. So, let’s say that the URL used for accessing Jenkins is Jenkins.example_server.com.
Now the moment Nginx receives the request with the server name as “Jenkins.example_server.com” and with the root context, it will hit the above server block. Now since the context is root, it will go to “location / ” block. Now Jenkins will know to hit “http://localhost:8085/jenkins/”  - the value from “proxy_pass”. Now Nginx will pass the user request to backend Jenkins and once it gets the response, it will replace tags in the response html which has the value as “http://localhost:8085/jenkins”  with the new value “Jenkins.example_server.com/jenkins” .


Now when the user clicks on any link with value “Jenkins.example_server.com/Jenkins/*”, the “location /jenkins” will be hit and accordingly the set of actions will be executed

Comments

Popular Posts