Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: A Three-Tier Web App on Containers with Pulumi

Design a three-tier web application with Pulumi: VPC and subnets, load balancer, container service, managed database, security groups, secrets and sizing per environment, with testable network logic.

The classic production layout has three tiers: a public load balancer, a private application layer running containers, and a private database. In this project you will plan the network, the security rules and the environment sizing, and see how the Pulumi program ties them together.

The cloud cannot be reached from this site, so the Pulumi code is read-only. The runnable stand-ins implement the logic you most often get wrong and can test offline: carving subnets from a CIDR block, checking that security groups allow exactly the intended paths, and sizing resources per environment.

Architecture

flowchart TB
  Internet(("Internet")) --> ALB["Load balancer (public subnets)"]
  ALB --> App["App containers (private subnets)"]
  App --> DB[("Database (isolated subnets)")]
  App --> NAT["NAT gateway"]
  NAT --> Internet
  Sec["Secrets store"] -.-> App

Only the load balancer is reachable from outside; only the app can reach the database.

Design goals:

  1. Two availability zones, with one subnet per tier per zone.
  2. Security groups chain: internet to ALB on 443, ALB to app on 8080, app to database on 5432. Nothing else.
  3. The database password is a Pulumi secret and ends up in a secrets store, never in code or logs.
  4. dev is small and cheap; prod is highly available and protected.

The program, in pieces (read-only)

Network with the higher-level awsx package (check its current API before use):

TypeScript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
import * as awsx from "@pulumi/awsx";

const config = new pulumi.Config();
const env = pulumi.getStack();
const sizes = {
  dev:  { cpu: 256,  memory: 512,  desired: 1, dbClass: "db.t4g.micro",  multiAz: false },
  prod: { cpu: 1024, memory: 2048, desired: 3, dbClass: "db.m6g.large", multiAz: true  },
}[env as "dev" | "prod"];

const vpc = new awsx.ec2.Vpc("net", {
  cidrBlock: "10.20.0.0/16",
  numberOfAvailabilityZones: 2,
  natGateways: { strategy: env === "prod" ? "OnePerAz" : "Single" },
  tags: { environment: env },
});

Security groups form the chain:

TypeScript
const albSg = new aws.ec2.SecurityGroup("alb", {
  vpcId: vpc.vpcId,
  ingress: [{ protocol: "tcp", fromPort: 443, toPort: 443, cidrBlocks: ["0.0.0.0/0"] }],
  egress: [{ protocol: "-1", fromPort: 0, toPort: 0, cidrBlocks: ["0.0.0.0/0"] }],
});
const appSg = new aws.ec2.SecurityGroup("app", {
  vpcId: vpc.vpcId,
  ingress: [{ protocol: "tcp", fromPort: 8080, toPort: 8080, securityGroups: [albSg.id] }],
  egress: [{ protocol: "-1", fromPort: 0, toPort: 0, cidrBlocks: ["0.0.0.0/0"] }],
});
const dbSg = new aws.ec2.SecurityGroup("db", {
  vpcId: vpc.vpcId,
  ingress: [{ protocol: "tcp", fromPort: 5432, toPort: 5432, securityGroups: [appSg.id] }],
});

Database with a secret password:

TypeScript
const dbPassword = config.requireSecret("dbPassword");
const dbSubnets = new aws.rds.SubnetGroup("db", { subnetIds: vpc.isolatedSubnetIds });
const db = new aws.rds.Instance("db", {
  engine: "postgres",
  engineVersion: "16",
  instanceClass: sizes.dbClass,
  allocatedStorage: 20,
  dbName: "shop",
  username: "shop",
  password: dbPassword,
  multiAz: sizes.multiAz,
  dbSubnetGroupName: dbSubnets.name,
  vpcSecurityGroupIds: [dbSg.id],
  storageEncrypted: true,
  skipFinalSnapshot: env !== "prod",
  deletionProtection: env === "prod",
}, { protect: env === "prod" });

The container service uses awsx.ecs.FargateService with an awsx.lb.ApplicationLoadBalancer; the task receives DATABASE_HOST from db.address and the password from a secrets store reference rather than a plain environment variable. Add the ECS and ALB pieces following the current awsx documentation.

Important choices visible in the code:

  • protect and deletionProtection are on for prod only.
  • The password flows as an Output marked secret from config to the database. It never appears in clear text in state, previews or logs.
  • Environment differences are data (sizes), not separate programs.

Planning subnets

A /16 VPC needs to be split into subnets per tier and zone. Doing it by hand invites overlaps. This stand-in carves equal subnets from a CIDR block, the same job as Terraform's cidrsubnet, or the arithmetic hidden inside awsx.ec2.Vpc.

Node.js Stand-in: carve subnets for three tiers and two zones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If a block does not fit (count times the subnet size exceeds the VPC), real planners fail. Try carve("10.20.0.0/16", 17, 6) and notice that the blocks would run past 10.20.255.255; production code should check that.

Checking the security group chain

The most valuable test for this stack is: "the database accepts connections from the app tier and from nothing else". You can express security groups as data and test reachability without any cloud.

Node.js Stand-in: reachability between tiers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the real stack, the same table drives a unit test with mocks: instantiate the program, collect the SecurityGroup inputs and assert the same eight statements. Pair it with a policy that rejects 0.0.0.0/0 on any port except 443 on a load balancer (see Policy as Code with CrossGuard).

Per-environment configuration

Config files carry the differences:

YAML
# Pulumi.dev.yaml
config:
  aws:region: eu-central-1
  shop:image: ghcr.io/acme/shop:1.8.2
  shop:dbPassword:
    secure: AAABAH...          # encrypted by the stack's secrets provider
# Pulumi.prod.yaml
config:
  aws:region: eu-central-1
  shop:image: ghcr.io/acme/shop:1.8.2
  shop:domain: shop.example.com

Set the secret without leaving it in shell history: pulumi config set --secret dbPassword and type the value at the prompt, or pipe it from a password manager CLI.

Deployment and operations

  • Image rollouts: change shop:image in config (or pass it from CI) and run pulumi up; the service performs a rolling deployment. Roll back by deploying the previous image tag.
  • Schema migrations run as a separate one-off task before the new image starts; do not hide them in Pulumi.
  • Database protection: protect, deletionProtection and final snapshots stop a mistaken delete. The earlier lessons on previews and state explain how a replacement would show up.
  • Drift: run the scheduled refresh --expect-no-changes check from the CI lesson.
  • Cost: NAT gateways and multi-AZ databases dominate the bill. dev uses one NAT gateway and a single-AZ database on purpose.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the design, which sources may connect to the database on port 5432?

    The database security group references the app security group as its only source.
  2. 2. Why is the database password read with config.requireSecret?

    requireSecret returns an Output marked secret, which Pulumi encrypts and masks.
  3. 3. Why use protect and deletionProtection only in prod?

    Protection adds friction on purpose; it is worth it where data matters and is unwanted in disposable environments.
  4. 4. A subnet plan accidentally overlaps another. Which test catches it without a cloud account?

    CIDR arithmetic is pure logic, so it can be tested offline, and the cloud would reject overlapping subnets later anyway.

Summary

  • Three tiers: a public load balancer, private application containers and an isolated database across two zones.
  • Security groups chain by group reference, not by broad CIDR blocks.
  • Secrets stay Output secrets from config to the resource; sizes and protection depend on the stack.
  • Network math and reachability are pure logic you can test offline.
  • Operations (rollouts, migrations, drift checks, cost) belong in the plan from day one.

Next: Project: A Multi-Environment Platform with Stack References