Install/Update Nginx to the latest stable version on Ubuntu

If you're using nginx on Ubuntu, you'll quickly discover that the default Ubuntu version bundled with the operating system is quite outdated. This implies the necessity of running the latest Nginx version to mitigate potential security issues. This article guides you through the process of upgrading the nginx to the latest stable version on Ubuntu.

To check your current Nginx version, run the following command:

nginx -v

Now, to update nginx to the latest stable version on Ubuntu, you can follow these steps.

1. Backup configuration

Before you update nginx, it's a good practice to back up your current nginx configuration. Run the following command to backup:

sudo cp -r /etc/nginx /etc/nginx_backup

2. Install the prerequisites

sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring

3. Improt nginx signing key

Import the official nginx signing key so apt could verify the packages authenticity. Run the following command to fetch the key:

curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
    | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

Now, verify that the downloaded file contains the proper key by running the following command:

gpg --dry-run --quiet --no-keyring --import --import-options import-show /usr/share/keyrings/nginx-archive-keyring.gpg

The output should contain the full fingerprint 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62. If the fingerprint is different, remove the file immediately and do not proceed further.

4. Install/Update latest stable version

Run the following command to set up the apt repository for stable nginx packages:

echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list

Now, set up repository pinning to prefer nginx packages the over operating system:

echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" \
    | sudo tee /etc/apt/preferences.d/99nginx

Finally, to install/update nginx, run the following command:

sudo apt update && sudo apt install nginx

during the update, the above command might ask for your input for /etc/nginx/nginx.conf file. You can provide input as per your choice.

5. Check nginx status

Run the following command to check if nginx is running:

sudo service nginx status

if it is running then it is ok. If it is not running and showing failed. then we need to start nginx again.

Run the following two commands to start the nginx and check the nginx status. It should be active (running) this time

sudo service nginx start
sudo service nginx status


You've successfully subscribed to Developer Insider
Great! Next, complete checkout for full access to Developer Insider
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.