How to Install SonarQube with Let's Encrypt on Ubuntu 20.04

Channel: Linux
Abstract: modify the user that will run the SonarQube service by editing the file shown. $ sudo vim /opt/sonarqube/bin/linux-x86-64/sonar.sh Scroll down and ens

It's every developer's dream to have clean and issue-free code which can readily be deployed into staging and production environments. One tool that can help you achieve this is in your CI/CD pipeline is SonarQube. SonarQube is a cross-platform and web-based tool used for continuous inspection of source code. It is written in Java. SonarQube enables you to write cleaner and safer code by inspecting code and detecting bugs and other inconsistencies.

SonarQube can be integrated into platforms such as GitHub, Gitlab, BitBucket, and Azure DevOps to mention a few platforms. It comes in various editions including Community, Developer, Enterprise, and Datacenter editions.

In this tutorial, we learn how to install SonarQube on Ubuntu 20.04. We will install the Community edition since it's free to download and enable SSL certificate (https) with Let's Encrypt by setting Nginx as a reverse proxy.

Own Unlimited Free VPN Server Setup...

To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video

Own Unlimited Free VPN Server Setup Ubuntu on Free VPS | SSH | SSL TLS | Squid Proxy | OpenVPN Prerequisites

Before you get started out, ensure that you meet the following requirements:

  1. Ubuntu 20.04 LTS with a sudo user configured.
  2. Ensure your system has a minimum of 4GB RAM and 2vCPU cores

You will need to install some tools

$ sudo apt update
$ sudo apt install net-tools unzip vim curl

Also, you need to increase the virtual memory kernel

$ sudo sysctl -w vm.max_map_count=262144

with the maximum number of open files

$ sudo sysctl -w fs.file-max=65536

and the resource limits

$ ulimit -n 65536
$ ulimit -u 4096

You can make the changes persistent by modifying system parameters in the /etc/sysctl.conf configuration file

$ sudo vim /etc/sysctl.conf

Add the following lines.

vm.max_map_count=262144
fs.file-max=65536
ulimit -n 65536
ulimit -u 4096

Save and exit. Thereafter, open the limits.conf file

$ sudo vim /etc/security/limits.conf

At the very bottom, add the following lines

sonarqube - nofile 65536
sonarqube - nproc 4096

Save and exit. For the changes to come into effect, reboot your server.

Step 1: Install OpenJDK

Since it is written in Java, SonarQube depends on Java to function. We will install OpenJDK 11 which provides java.

$ sudo apt install openjdk-11-jdk

Once installed, you can verify the version of Java.

$ java -version
Step 2: Install PostgreSQL database

From 2016, SonarQube dropped support for MySQL and now only supports PostgreSQL. As such, we need to install the PostgreSQL database.

To start off, download and add the PostgreSQL GPG key.

$ wget -q https://www.postgresql.org/media/keys/ACCC4CF8.asc -O - | sudo apt-key add -

Thereafter, add the PostgreSQL repository.

$ sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" >> /etc/apt/sources.list.d/pgdg.list'

Then update the package index to sync the new repository.

$ sudo apt update

Once you are done updating the package lists, install the PostgreSQL database and its dependencies.

$ sudo apt install postgresql postgresql-contrib

By default, the PostgreSQL service gets started after installation, if not started run the following command.

$ sudo systemctl start postgresql

Just to confirm that everything is running as expected, verify its running status.

$ sudo systemctl status postgresql

You can also confirm the port it's listening on:

$ sudo netstat -pnltu | grep 5432
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      7768/postgres       
tcp6       0      0 ::1:5432                :::*                    LISTEN      7768/postgres    

Enable PostgreSQL to automatically start upon booting:

$ sudo systemctl enable postgresql

So far, our PostgreSQL is up and running without any hitches.

Step 3: Configure PostgreSQL

Moving on, we are going to set the password for the Postgres user that usually comes by default when PostgreSQL is installed. To do so, run the command:

$ sudo passwd postgres

Type the password and confirm it. Next, switch to the Postgres user.

$ su - postgres

Next, proceed and create a new database user.

$ createuser sonar

Once done, switch to the PostgreSQL prompt using the command:

$ psql

With access to the PostgreSQL shell, create a password for the user you just created.

 ALTER USER sonar WITH ENCRYPTED PASSWORD 'strong_password';

Next, create a SonarQube database with the user you created as the owner

CREATE DATABASE sonarqube OWNER sonar;

Then, assign or grant all privileges to the database use such that they have all the privileges to modify the database.

GRANT ALL PRIVILEGES ON DATABASE sonarqube to sonar;

Now exit the database.

\q
Step 4: Download and configure SonarQube

Moving on, we are going to download the latest SonarQube binary zip file. At the moment, the latest Community Edition release, which is a Long Term Service ( LTS ) release is SonarQube version 9.0.1. You can head over to SonarQube download page for the latest downloads.

To download the zip file, issue the command:

$ wget https://binaries.sonarsource.com/Distribution/sonarqube/sonarqube-9.0.1.46107.zip 

Next, unzip the zipped file.

$ unzip sonarqube-9.0.1.46107.zip

And move it to the /opt/ path.

$ sudo mv sonarqube-9.0.1.46107 /opt/sonarqube
Step 5: Create new user and group

Moving on, we will create a new user and group that will run the SonarQube service. So, create the group.

$ sudo groupadd sonar

Next, create the user with the home directory set to /opt/sonarqube as you add the user to the newly created group.

$ sudo useradd -c "SonarQube - User" -d /opt/sonarqube/ -g sonar sonar

Then set ownership to the /opt/sonarqube directory.

$ sudo chown -R sonar:sonar /opt/sonarqube/
Step 6: Configure SonarQube

Let's now configure SonarQube. Open the SonarQube configuration file.

$ sudo vim  /opt/sonarqube/conf/sonar.properties

Locate and uncomment the following lines

sonar.jdbc.username=
sonar.jdbc.password=

These represent the SonarQube database user and password that we created in the PostgreSQL database server. Therefore, fill in the values accordingly.

sonar.jdbc.username=sonar_user
sonar.jdbc.password=strong_password

Next, modify these lines so that they look as what is provided

sonar.jdbc.url=jdbc:postgresql://localhost:5432/sonarqube
sonar.search.javaOpts=-Xmx512m -Xms512m -XX:MaxDirectMemorySize=256m -XX:+HeapDumpOnOutOfMemoryError

Thereafter, modify the following lines to appear as they look.

sonar.web.host=0.0.0.0
sonar.web.port=9000
sonar.web.javaAdditionalOpts=-server
sonar.log.level=INFO
sonar.path.logs=logs

Next, modify the user that will run the SonarQube service by editing the file shown.

$ sudo vim /opt/sonarqube/bin/linux-x86-64/sonar.sh

Scroll down and ensure the line below appears as shown.

RUN_AS_USER=sonar
Step 7: Create a Systemd service file for SonarQube

At the moment, our system has no way of starting the SonarQube service. Therefore, we need to create a systemd service. To do so, run the command:

$ sudo vim  /etc/systemd/system/sonarqube.service

Add the following lines.

[Unit]
Description=SonarQube service
After=syslog.target network.target

[Service]
Type=forking
ExecStart=/opt/sonarqube/bin/linux-x86-64/sonar.sh start
ExecStop=/opt/sonarqube/bin/linux-x86-64/sonar.sh stop
User=sonar
Group=sonar
Restart=always
LimitNOFILE=65536
LimitNPROC=4096

[Install]
WantedBy=multi-user.target

Save the changes and exit the file.

Enable the SonarQube service to start upon booting

$ sudo systemctl enable sonarqube

And start the SonarQube service.

$ sudo systemctl start sonarqube

To ensure that the SonarQube service is running, execute the command:

$ sudo systemctl status sonarqube

Also, ensure that port 9000 is opened

$ sudo ufw allow '9000'
Rules updated
Rules updated (v6)

Check if the service is listening on port 9000

$ sudo netstat -pnltu | grep 9000
tcp6       0      0 :::9000                 :::*                    LISTEN      65140/java  

Now you can try to check if you can access the login page by entering the public IP of your server and the port number from your browser ie http://<server-ip>:9000/. The default administrator user name is 'admin' and the password is 'admin'.

Sonarqube will request you to update the password in order to change the default one.

Step 8: Install and Configure Nginx with SSL (optional)

In order to access your Sonarqube with SSL enabled domain name, you will need to install a reverse proxy like Nginx. The webserver will proxy connections to SonarQube so that developers can access it from a secured domain name.

Installing Nginx is simple and straightforward and can be done in one single command.

$ sudo apt install nginx

After the installation, enable the Nginx webserver to start on boot time.

$ sudo systemctl enable nginx

And start the service

$ sudo systemctl start nginx

For the webserver to be aware of SonarQube, we are going to create a configuration file shown.

$ sudo vim  /etc/nginx/sites-available/sonarqube.conf

Then paste the content provided.

server {

listen 80;
server_name example.com or SERVER-IP;
access_log /var/log/nginx/sonar.access.log;
error_log /var/log/nginx/sonar.error.log;
proxy_buffers 16 64k;
proxy_buffer_size 128k;

location / {
proxy_pass http://127.0.0.1:9000;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_redirect off;
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_set_header X-Forwarded-Proto http;
}
}

Save and exit. Then enable the Sonarqube site:

$ sudo ln -s /etc/nginx/sites-available/sonarqube.conf  /etc/nginx/sites-enabled/sonarqube.conf

Check if the configuration is correct

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Then restart the Nginx web server for the changes to be applied.

$ sudo systemctl restart nginx

Now we need to configure the UFW firewall to allow nginx. To accomplish this, run the commands

$ sudo ufw allow 'Nginx Full'

Then reload the firewall to effect the changes.

$ sudo ufw --reload

You can now access your SonarQube with through its domain name

Here, we are going to use the free let's encrypt certificate. To configure that we need to run cerbot for Nginx:

$ sudo certbot --nginx
Saving debug log to /var/log/letsencrypt/letsencrypt.log
 Plugins selected: Authenticator nginx, Installer nginx
 Enter email address (used for urgent renewal and security notices) (Enter 'c' to
 cancel): [email protected]                                                    
 
 Please read the Terms of Service at
 https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
 agree in order to register with the ACME server at
 https://acme-v02.api.letsencrypt.org/directory
 
 (A)gree/(C)ancel: A
 
 Would you be willing to share your email address with the Electronic Frontier
 Foundation, a founding partner of the Let's Encrypt project and the non-profit
 organization that develops Certbot? We'd like to send you email about our work
 encrypting the web, EFF news, campaigns, and ways to support digital freedom.
 
 (Y)es/(N)o: N
Saving debug log to /var/log/letsencrypt/letsencrypt.log
 Plugins selected: Authenticator nginx, Installer nginx
 Which names would you like to activate HTTPS for?
 
 1: websitefortesting.com
 
 Select the appropriate numbers separated by commas and/or spaces, or leave input
 blank to select all options shown (Enter 'c' to cancel): 1
 Obtaining a new certificate
 Performing the following challenges:
 http-01 challenge for websitefortesting.com
 Waiting for verification…
 Cleaning up challenges
 Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/sonarqube.conf
 Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
 
 1: No redirect - Make no further changes to the webserver configuration.
 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
 new sites, or if you're confident your site works on HTTPS. You can undo this
 change by editing your web server's configuration.
 
 Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
 Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/sonarqube.conf
 
 Congratulations! You have successfully enabled https://websitefortesting.com
 You should test your configuration at:
 https://www.ssllabs.com/ssltest/analyze.html?d=websitefortesting.com
 
 IMPORTANT NOTES:
 Congratulations! Your certificate and chain have been saved at:
 /etc/letsencrypt/live/websitefortesting.com/fullchain.pem
 Your key file has been saved at:
 /etc/letsencrypt/live/websitefortesting.com/privkey.pem
 Your cert will expire on 2021-11-27. To obtain a new or tweaked
 version of this certificate in the future, simply run certbot again
 with the "certonly" option. To non-interactively renew all of
 your certificates, run "certbot renew"
 If you like Certbot, please consider supporting our work by:
 Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
 Donating to EFF:                    https://eff.org/donate-le 

By default, let's encrypt will add some lines in the Nginx server block file.

You should have something like this

server {
         server_name websitefortesting.com;
         add_header Strict-Transport-Security max-age=2592000;
         #rewrite ^ https://$server_name$request_uri? permanent;
         access_log  /var/log/nginx/sonarqube.access.log;
         error_log   /var/log/nginx/sonarqube.error.log;
     proxy_buffers 16 64k;     
           proxy_buffer_size 128k;     

           location / {
             proxy_pass http://127.0.0.1:9000;            
             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_set_header X-Forwarded-Proto http;     
           } 
          listen 443 ssl; # managed by Certbot 
          ssl_certificate /etc/letsencrypt/live/websitefortesting.com/fullchain.pem; # managed by Certbot 
           ssl_certificate_key /etc/letsencrypt/live/websitefortesting.com/privkey.pem; # managed by Certbot 
          include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot 
          ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
 }
 server {
     if ($host = websitefortesting.com) {
         return 301 https://$host$request_uri;
     } # managed by Certbot
     
            listen 80;     
            server_name websitefortesting.com; return 404; # managed by Certbot

 }
Step 10: Access SonarQube with HTTPS

Now you can access SonarQube securely with HTTPS URL configured with let's encrypt.

https://domain-name

After login, you will get the landing page shown.

Conclusion

In this tutorial, we learned how to install SonarQube on Ubuntu 20.04. We have enabled Sonarqube with SSL using Let's Encrypt certificate using Nginx as a reverse proxy.

Ref From: linoxide
Channels:

Related articles