Skip to content
Advertisement

Running PHP locally with Ubuntu

I am using Ubuntu 18.04 on Google Cloud Platform and I’m trying to run a test file called login.php. The path is /var/www/login.php. Whenever I try running it, I use sudo php -f /var/www/login.php then check http://localhost/var/www/login.php on my web browser. However, my web browser returns with This site can’t be reached, localhost refused to connect. I have looked everywhere for a solution but my web browser always comes back with an error.

Advertisement

Answer

You shouldn’t use http://localhost to reach your VM running in GCP.

To solve your issue you should follow the documentation Built-in web server, also you should configure network tags for your VM instance and create new firewall rule.

Please have a look on my steps below:

  1. create VM instance:
$ gcloud compute instances create instance-1 --zone=us-central1-a --machine-type=n1-standard-1 --image=ubuntu-1804-bionic-v20200610 --image-project=ubuntu-os-cloud 
  1. configure network tag on VM instance:
$ gcloud compute instances create instance-1 --zone=us-central1-a --tags=php-http-server
  1. create firewall rule to allow inbound traffic on port 8080:
$ gcloud compute firewall-rules create allow-php-http-8080 --direction=INGRESS --priority=1000 --network=default --action=ALLOW --rules=tcp:8080 --source-ranges=0.0.0.0/0 --target-tags=php-http-server
  1. install php 7.2:
$ sudo apt update
$ sudo apt upgrade
$ sudo apt install php7.2
  1. create index.php file:
$ cd /var/www/
$ cat index.php 
<?php
echo 'Hello World!';
?>
  1. start a PHP web server from the folder with index.php file:
$ php -S localhost:8080
PHP 7.2.24-0ubuntu0.18.04.6 Development Server started at Thu Jun 18 12:31:16 2020
Listening on http://localhost:8080
Document root is /var/www
Press Ctrl-C to quit.
  1. check connection from VM instance (via secondary SSH connection):
$ curl http://localhost:8080
Hello World!
  1. start a PHP web server on internal IP of your VM instance:
$ php -S 10.128.0.4:8080
PHP 7.2.24-0ubuntu0.18.04.6 Development Server started at Thu Jun 18 12:40:46 2020
Listening on http://10.128.0.4:8080
Document root is /var/www
Press Ctrl-C to quit.
  1. check connection from on-premises on external IP of your VM:
$ curl http://34.XXX.XXX.121:8080
Hello World!

same result via web browser at http://34.XXX.XXX.121:8080:

Hello World!

In addition, have a look at Getting started with PHP on Compute Engine to see an alternative solution.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement