基于GCP Cloud Run部署简单HTML应用遇端口启动问题求助
问题原因
Cloud Run 不会固定使用80端口,而是通过**PORT环境变量**动态分配端口给容器。你的Nginx配置硬编码了listen 80,导致容器没有监听Cloud Run指定的端口,触发健康检查失败,进而部署报错。
解决步骤
1. 修改Nginx配置文件
将nginx.conf中的固定端口改为环境变量占位符,本地测试时默认用80:
server { listen ${PORT:-80}; location / { root /usr/share/nginx/html/; include /etc/nginx/mime.types; try_files $uri $uri/ /index.html; } }
2. 修改Dockerfile的启动命令
Nginx默认不支持直接解析环境变量,需要在启动时用envsubst替换配置文件中的变量:
FROM nginx:latest RUN rm /usr/share/nginx/html/index.html RUN rm /usr/share/nginx/html/50x.html COPY index.html /usr/share/nginx/html/ COPY style.css /usr/share/nginx/html/ COPY nginx.conf /etc/nginx/conf.d/default.conf EXPOSE 80 CMD envsubst '${PORT}' < /etc/nginx/conf.d/default.conf > /etc/nginx/conf.d/default.conf.tmp && mv /etc/nginx/conf.d/default.conf.tmp /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'
3. 本地验证(可选)
设置PORT环境变量测试镜像是否正常工作:
docker build -t test-image . docker run -p 8080:8080 -e PORT=8080 test-image
访问http://localhost:8080确认应用正常。
4. 重新部署
重新构建并推送镜像到Docker Hub,再通过Cloud Run UI部署即可。此时Cloud Run会自动传递PORT变量,Nginx会监听正确的端口,通过健康检查。
内容的提问来源于stack exchange,提问作者Philly
相关产品推荐
相关产品推荐

