使用Terraform部署Azure App Service Docker容器时如何指定端口
问题背景
- 参考Linux App Service运行Docker容器的示例编写Terraform配置,初始
main.tf内容如下:
provider "azurerm" { features {} } resource "azurerm_resource_group" "example" { name = "${var.prefix}-resources" location = var.location } resource "azurerm_service_plan" "example" { name = "${var.prefix}-sp-zipdeploy" location = azurerm_resource_group.example.location resource_group_name = azurerm_resource_group.example.name os_type = "Linux" sku_name = "S1" } resource "azurerm_linux_web_app" "example" { name = "${var.prefix}-example" location = azurerm_resource_group.example.location resource_group_name = azurerm_resource_group.example.name service_plan_id = azurerm_service_plan.example.id app_settings = { "WEBSITES_ENABLE_APP_SERVICE_STORAGE" = "false" } site_config { application_stack { docker_image = "ghcr.io/moja-global/rest_api_flint.example" docker_image_tag = "master" } } }
- 执行
terraform init、terraform apply完成部署后应用无法访问,排查确认配置缺少容器运行端口相关设置。本地运行该镜像时通过-p参数映射了8080端口,对应命令如下:
docker pull ghcr.io/moja-global/rest_api_flint.example:master docker run --rm -p 8080:8080 ghcr.io/moja-global/rest_api_flint.example
- 需要在Terraform配置中添加对应端口设置,让应用在Azure App Service上正常对外提供访问。
解决方案
Azure Linux App Service运行自定义单Docker容器时,平台内置的反向代理默认会把入站流量转发到容器的80端口,不需要手动配置类似docker run -p的端口映射规则,只需要通过应用设置告知平台容器实际监听的端口即可。
你的容器实际监听8080端口,直接在azurerm_linux_web_app资源的app_settings块中添加WEBSITES_PORT配置项,值设为8080即可,修改后的Web App资源配置如下:
resource "azurerm_linux_web_app" "example" { name = "${var.prefix}-example" location = azurerm_resource_group.example.location resource_group_name = azurerm_resource_group.example.name service_plan_id = azurerm_service_plan.example.id app_settings = { "WEBSITES_ENABLE_APP_SERVICE_STORAGE" = "false" # 指定容器实际监听端口,平台会自动转发流量到该端口 "WEBSITES_PORT" = "8080" } site_config { application_stack { docker_image = "ghcr.io/moja-global/rest_api_flint.example" docker_image_tag = "master" } } }
配置修改完成后执行terraform apply提交更新,等待资源部署完成、容器重启加载配置(一般需要1-3分钟),就可以通过App Service的默认域名正常访问应用。
提一句:如果是使用Docker Compose部署多容器场景,
WEBSITES_PORT参数不生效,需要在Compose配置文件中明确声明端口映射规则。
内容的提问来源于stack exchange,提问作者Harsh Mishra
相关产品推荐
相关产品推荐

