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:
- 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
- configure network tag on VM instance:
$ gcloud compute instances create instance-1 --zone=us-central1-a --tags=php-http-server
- 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
- install php 7.2:
$ sudo apt update $ sudo apt upgrade $ sudo apt install php7.2
- create
index.php
file:
$ cd /var/www/ $ cat index.php <?php echo 'Hello World!'; ?>
- 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.
- check connection from VM instance (via secondary SSH connection):
$ curl http://localhost:8080 Hello World!
- 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.
- 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.