在Ubuntu上本地运行PHP

时间:2020-06-18 11:13:51

标签: php google-cloud-platform ubuntu-18.04

我正在Google Cloud Platform上使用Ubuntu 18.04,并且试图运行名为login.php的测试文件。路径为/var/www/login.php。每当尝试运行它时,我都会使用sudo php -f /var/www/login.php,然后在网络浏览器中检查 http://localhost/var/www/login.php 。但是,我的网络浏览器返回无法访问此站点,本地主机拒绝连接。。我到处都在寻找解决方案,但我的网络浏览器总是返回错误。

1 个答案:

答案 0 :(得分:2)

您不应使用http://localhost来访问在GCP中运行的VM。

要解决您的问题,请遵循文档Built-in web server,还应为VM实例配置network tags并创建新的firewall rule

请在下面查看我的步骤:

  1. 创建VM实例:
$ 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 
    VM实例上的
  1. configure网络标记:
$ gcloud compute instances create instance-1 --zone=us-central1-a --tags=php-http-server
  1. create防火墙规则以允许端口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. 安装php 7.2:
$ sudo apt update
$ sudo apt upgrade
$ sudo apt install php7.2
  1. 创建index.php文件:
$ cd /var/www/
$ cat index.php 
<?php
echo 'Hello World!';
?>
  1. 从带有index.php文件的文件夹中启动PHP Web服务器:
$ 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. 检查来自VM实例的连接(通过辅助SSH连接):
$ curl http://localhost:8080
Hello World!
  1. 在您的VM实例的内部IP上启动PHP Web服务器:
$ 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. 在VM的外部IP上从本地检查连接:
$ curl http://34.XXX.XXX.121:8080
Hello World!

通过网络浏览器在http://34.XXX.XXX.121:8080上获得相同的结果:

Hello World!

此外,请查看Getting started with PHP on Compute Engine来了解替代解决方案。