Install nginx on Google Cloud VM

By | 05/12/2019

This took a little work as there seems to be a bug in DEbian & nginx – here’s how I got it working.

ssh into your GCP VM and run the following commands to update and upgrade the system.

$ sudo apt update
$ sudo apt upgrade

Install nginx

$ sudo apt install nginx

Check it’s all working by running

$ sudo systemctl status nginx

This is where I hit the bug. I received the following error in the output:

nginx.service: Failed to read PID from file /run/nginx.pid: Invalid argument

The workaround thanks to stack is

$ mkdir /etc/systemd/system/nginx.service.d
$ printf "[Service]\nExecStartPost=/bin/sleep 0.1\n" > /etc/systemd/system/nginx.service.d/override.conf
$ systemctl daemon-reload
$ systemctl restart nginx 

However when I ran the printf command I received an error:
-bash: /etc/systemd/system/nginx.service.d/override.conf: Permission denied

If you read a little further down the stackoverflow thread you need to run sudo su and then the command:

$ sudo su
$ printf "[Service]\nExecStartPost=/bin/sleep 0.1\n" > /etc/systemd/system/nginx.service.d/override.conf
$ systemctl daemon-reload
$ systemctl restart nginx 
$ exit # exit from su

If you run

$ sudo systemctl status nginx

You should see

Starting A high performance web server and a reverse proxy server…
Started A high performance web server and a reverse proxy server.

Now to install the firewall

$ sudo apt install ufw
$ sudo ufw allow ssh # Allow ssh ports
$ sudo ufw allow 'Nginx Full' # allow all ports for nginx
$ sudo ufw enable

To check the status from the terminal run

$ sudo ufw status

You should see the following output

To                         Action      From
—                         ——      —-
22/tcp                     ALLOW IN    Anywhere                  
80,443/tcp (Nginx Full)    ALLOW IN    Anywhere                  
22/tcp (v6)                ALLOW IN    Anywhere (v6)             
80,443/tcp (Nginx Full (v6)) ALLOW IN    Anywhere (v6)  

If you head to your browser and the VM IP address you should see the Welcome to nginx! message. Remember to run http://xxx.xxx.x.x NOT https://xxx.xxx.x.x