DevOps Hive

Patterns / Deploy an app

Deploy a web app on AWS App Runner with Postgres and Redis

Run a container on App Runner with an RDS Postgres database and an ElastiCache Redis that only the app can reach. The database password is generated for you and never appears in your code.

  1. Browser
  2. App Runner
  3. VPC connector
  4. Postgres and Redis

How it works

  1. Why the database needs its own network

    App Runner gives your container a public HTTPS address, which is what you want for the app. It is not what you want for the database. A database with a public address is one leaked password away from being read by anyone, so the database and the cache go in private subnets with no route from the internet.

  2. Build the private network

    The configuration creates a VPC with two private subnets in two availability zones, because RDS and ElastiCache both require two. Security group rules name the app's security group as the only allowed source. Nothing uses an address range, so there is no 0.0.0.0/0 rule to forget about.

  3. Create Postgres and Redis

    Postgres runs with encrypted storage, seven days of backups and deletion protection on. Redis runs as a single small node with encryption at rest and in transit, so the app connects with a rediss:// address. For a test you plan to throw away, set deletion_protection to false and apply before you destroy.

  4. Generate the password and store the connection string

    OpenTofu generates a 32 character password and writes the full connection string to Secrets Manager. The app receives it as the DATABASE_URL environment variable when an instance starts. The password is also held in the OpenTofu state, so keep the state in an encrypted backend with restricted access.

  5. Connect App Runner to the network

    A VPC connector sends the app's outgoing traffic into the private subnets so it can reach the database and cache. The mistake people make here: once the connector is on, all outgoing traffic goes through the VPC, and this VPC has no NAT gateway. If your app calls an outside API, such as a payment or email provider, add a NAT gateway or those calls will time out.

  6. Deploy a new version

    Push a new image to ECR with a new tag, change the image variable and apply. App Runner starts the new version, waits for the health check path to answer, then moves traffic over.

What you set

name
Short prefix for every resource For example web-app
image
ECR image URI with tag For example 111122223333.dkr.ecr.us-east-1.amazonaws.com/web-app:1a2b3c4
container_port
Port the container listens on For example 8080
health_check_path
Path that returns 200 when the app is ready For example /health

What it costs to run

About $50 to $110 a month for one always-on App Runner instance (1 vCPU, 2 GB), a db.t4g.micro Postgres and a cache.t4g.micro Redis. Traffic and database storage move it up, and a NAT gateway adds roughly $35. Estimate.

The configuration

# A containerised web app on AWS App Runner with Postgres and Redis.
#
# What this creates:
#   - a VPC with two private subnets (no internet gateway, nothing public)
#   - an RDS Postgres instance and an ElastiCache Redis, reachable only from the app
#   - a generated database password, stored as a connection string in Secrets Manager
#   - an App Runner service that pulls your image from ECR and reaches the
#     database and cache through a VPC connector

terraform {
  required_version = ">= 1.6.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.6"
    }
  }
}

provider "aws" {
  region = var.region
}

variable "region" {
  description = "AWS region to deploy into."
  type        = string
  default     = "us-east-1"
}

variable "name" {
  description = "Short name used as a prefix for every resource, lowercase with hyphens."
  type        = string
}

variable "image" {
  description = "Full ECR image URI with tag, for example 111122223333.dkr.ecr.us-east-1.amazonaws.com/web-app:1a2b3c4."
  type        = string
}

variable "container_port" {
  description = "Port the container listens on."
  type        = string
  default     = "8080"
}

variable "health_check_path" {
  description = "Path App Runner calls to decide whether an instance is healthy."
  type        = string
  default     = "/health"
}

variable "vpc_cidr" {
  description = "Address range for the VPC."
  type        = string
  default     = "10.20.0.0/16"
}

variable "db_name" {
  description = "Name of the database created inside the Postgres instance."
  type        = string
  default     = "app"
}

variable "db_instance_class" {
  description = "RDS instance size."
  type        = string
  default     = "db.t4g.micro"
}

variable "redis_node_type" {
  description = "ElastiCache node size."
  type        = string
  default     = "cache.t4g.micro"
}

variable "deletion_protection" {
  description = "Blocks deleting the database. Set to false, apply, then destroy when you tear down a test."
  type        = bool
  default     = true
}

data "aws_availability_zones" "available" {
  state = "available"
}

# --- Network -----------------------------------------------------------------

resource "aws_vpc" "main" {
  cidr_block           = var.vpc_cidr
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Name = var.name
  }
}

# Two subnets in two zones: RDS and ElastiCache subnet groups both need at
# least two. There is no internet gateway, so nothing here has a public address.
resource "aws_subnet" "private" {
  count             = 2
  vpc_id            = aws_vpc.main.id
  cidr_block        = cidrsubnet(var.vpc_cidr, 8, count.index)
  availability_zone = data.aws_availability_zones.available.names[count.index]

  tags = {
    Name = "${var.name}-private-${count.index}"
  }
}

resource "aws_security_group" "app" {
  name        = "${var.name}-app"
  description = "App Runner VPC connector"
  vpc_id      = aws_vpc.main.id
}

resource "aws_security_group" "db" {
  name        = "${var.name}-db"
  description = "Postgres, reachable from the app only"
  vpc_id      = aws_vpc.main.id
}

resource "aws_security_group" "redis" {
  name        = "${var.name}-redis"
  description = "Redis, reachable from the app only"
  vpc_id      = aws_vpc.main.id
}

# The rules name security groups, not address ranges, so only traffic that
# comes through the connector reaches the database and the cache.
resource "aws_vpc_security_group_egress_rule" "app_to_db" {
  security_group_id            = aws_security_group.app.id
  referenced_security_group_id = aws_security_group.db.id
  ip_protocol                  = "tcp"
  from_port                    = 5432
  to_port                      = 5432
}

resource "aws_vpc_security_group_egress_rule" "app_to_redis" {
  security_group_id            = aws_security_group.app.id
  referenced_security_group_id = aws_security_group.redis.id
  ip_protocol                  = "tcp"
  from_port                    = 6379
  to_port                      = 6379
}

resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
  security_group_id            = aws_security_group.db.id
  referenced_security_group_id = aws_security_group.app.id
  ip_protocol                  = "tcp"
  from_port                    = 5432
  to_port                      = 5432
}

resource "aws_vpc_security_group_ingress_rule" "redis_from_app" {
  security_group_id            = aws_security_group.redis.id
  referenced_security_group_id = aws_security_group.app.id
  ip_protocol                  = "tcp"
  from_port                    = 6379
  to_port                      = 6379
}

# --- Postgres ----------------------------------------------------------------

# No special characters, so the password is safe inside a connection URL.
# The value is also kept in the OpenTofu state, so keep the state in an
# encrypted backend that only your team can read.
resource "random_password" "db" {
  length  = 32
  special = false
}

resource "aws_db_subnet_group" "main" {
  name       = var.name
  subnet_ids = aws_subnet.private[*].id
}

resource "aws_db_instance" "main" {
  identifier     = var.name
  engine         = "postgres"
  engine_version = "16"
  instance_class = var.db_instance_class

  allocated_storage     = 20
  max_allocated_storage = 100
  storage_type          = "gp3"
  storage_encrypted     = true

  db_name  = var.db_name
  username = "app"
  password = random_password.db.result

  db_subnet_group_name   = aws_db_subnet_group.main.name
  vpc_security_group_ids = [aws_security_group.db.id]
  publicly_accessible    = false

  backup_retention_period    = 7
  auto_minor_version_upgrade = true

  # Both settings protect data on teardown. For a throwaway test, set
  # deletion_protection to false and apply before running destroy.
  deletion_protection       = var.deletion_protection
  skip_final_snapshot       = false
  final_snapshot_identifier = "${var.name}-final"
}

# --- Redis -------------------------------------------------------------------

resource "aws_elasticache_subnet_group" "main" {
  name       = var.name
  subnet_ids = aws_subnet.private[*].id
}

resource "aws_elasticache_replication_group" "main" {
  replication_group_id = var.name
  description          = "Cache for ${var.name}"
  engine               = "redis"
  engine_version       = "7.1"
  node_type            = var.redis_node_type
  port                 = 6379

  # One node keeps the cost down. Raise num_cache_clusters to 2 and turn on
  # automatic_failover_enabled when losing the cache would take the app down.
  num_cache_clusters         = 1
  automatic_failover_enabled = false

  at_rest_encryption_enabled = true
  transit_encryption_enabled = true

  subnet_group_name  = aws_elasticache_subnet_group.main.name
  security_group_ids = [aws_security_group.redis.id]
}

# --- Connection string in Secrets Manager -------------------------------------

resource "aws_secretsmanager_secret" "database_url" {
  name        = "${var.name}/database-url"
  description = "Postgres connection string for ${var.name}"
}

resource "aws_secretsmanager_secret_version" "database_url" {
  secret_id     = aws_secretsmanager_secret.database_url.id
  secret_string = "postgres://${aws_db_instance.main.username}:${random_password.db.result}@${aws_db_instance.main.address}:5432/${var.db_name}"
}

# --- IAM ---------------------------------------------------------------------

# Access role: App Runner itself uses it to pull the image from ECR.
data "aws_iam_policy_document" "access_trust" {
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["build.apprunner.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "access" {
  name               = "${var.name}-apprunner-access"
  assume_role_policy = data.aws_iam_policy_document.access_trust.json
}

resource "aws_iam_role_policy_attachment" "access" {
  role       = aws_iam_role.access.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSAppRunnerServicePolicyForECRAccess"
}

# Instance role: your running code uses it. It can read one secret and
# nothing else.
data "aws_iam_policy_document" "instance_trust" {
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["tasks.apprunner.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "instance" {
  name               = "${var.name}-apprunner-instance"
  assume_role_policy = data.aws_iam_policy_document.instance_trust.json
}

data "aws_iam_policy_document" "instance" {
  statement {
    sid       = "ReadDatabaseUrl"
    effect    = "Allow"
    actions   = ["secretsmanager:GetSecretValue"]
    resources = [aws_secretsmanager_secret.database_url.arn]
  }
}

resource "aws_iam_role_policy" "instance" {
  name   = "read-secrets"
  role   = aws_iam_role.instance.id
  policy = data.aws_iam_policy_document.instance.json
}

# --- App Runner --------------------------------------------------------------

resource "aws_apprunner_vpc_connector" "main" {
  vpc_connector_name = var.name
  subnets            = aws_subnet.private[*].id
  security_groups    = [aws_security_group.app.id]
}

resource "aws_apprunner_service" "main" {
  service_name = var.name

  source_configuration {
    # Deploys happen when you change var.image and apply, not on every push.
    auto_deployments_enabled = false

    authentication_configuration {
      access_role_arn = aws_iam_role.access.arn
    }

    image_repository {
      image_identifier      = var.image
      image_repository_type = "ECR"

      image_configuration {
        port = var.container_port

        runtime_environment_variables = {
          REDIS_URL = "rediss://${aws_elasticache_replication_group.main.primary_endpoint_address}:6379"
        }

        # App Runner reads the secret when an instance starts and passes it
        # to the container as an environment variable.
        runtime_environment_secrets = {
          DATABASE_URL = aws_secretsmanager_secret.database_url.arn
        }
      }
    }
  }

  instance_configuration {
    cpu               = "1024"
    memory            = "2048"
    instance_role_arn = aws_iam_role.instance.arn
  }

  # Incoming requests still arrive over the public App Runner address. Only
  # outgoing traffic goes through the VPC. With no NAT gateway in the VPC,
  # the app cannot call services on the internet.
  network_configuration {
    egress_configuration {
      egress_type       = "VPC"
      vpc_connector_arn = aws_apprunner_vpc_connector.main.arn
    }
  }

  health_check_configuration {
    protocol            = "HTTP"
    path                = var.health_check_path
    interval            = 10
    timeout             = 5
    healthy_threshold   = 1
    unhealthy_threshold = 5
  }

  # The service fails to start if the secret has no value yet or the role
  # cannot read it, so wait for both.
  depends_on = [
    aws_secretsmanager_secret_version.database_url,
    aws_iam_role_policy.instance,
    aws_iam_role_policy_attachment.access,
  ]
}

output "service_url" {
  description = "Public HTTPS address of the app."
  value       = "https://${aws_apprunner_service.main.service_url}"
}

output "service_arn" {
  description = "ARN of the App Runner service, for example to attach a web ACL."
  value       = aws_apprunner_service.main.arn
}

output "database_url_secret_arn" {
  description = "Secret that holds the Postgres connection string."
  value       = aws_secretsmanager_secret.database_url.arn
}

Works with OpenTofu 1.6 or later, and with Terraform. Read it before you apply it: it creates real resources in your account.

Written by DevOps Hive. Last updated 2026-11-27.

More in deploy an app