您不应使用http://localhost 访问在 GCP 中运行的虚拟机。
要解决您的问题,您应该遵循文档Built-in web server,还应该为您的VM 实例配置network tags 并创建新的firewall rule。
请看下面我的步骤:
- 创建虚拟机实例:
$ 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 网络标签:
$ gcloud compute instances create instance-1 --zone=us-central1-a --tags=php-http-server
-
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
- 安装php 7.2:
$ sudo apt update
$ sudo apt upgrade
$ sudo apt install php7.2
- 创建
index.php文件:
$ cd /var/www/
$ cat index.php
<?php
echo 'Hello World!';
?>
- 从包含
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.
- 检查来自 VM 实例的连接(通过辅助 SSH 连接):
$ curl http://localhost:8080
Hello World!
- 在您的 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.
- 检查您的 VM 外部 IP 上的本地连接:
$ curl http://34.XXX.XXX.121:8080
Hello World!
通过网络浏览器http://34.XXX.XXX.121:8080获得相同结果:
世界你好!
此外,请查看Getting started with PHP on Compute Engine 以了解替代解决方案。