An Infrastructure as Code (IaC) project using Terraform to provision and manage a multi-container application locally using the Docker provider consisting of a Node.js web app connected to a MongoDB database.
- Terraform — Infrastructure as Code
- Docker — Container runtime
- MongoDB 5.0 — Database
- Node.js Web App — Frontend/backend application
terraform-docker-infrastructure/ ├── .gitignore ├── main.tf ├── variables.tf ├── outputs.tf └── README.md
A dedicated Docker network (app-network) is created so containers
can communicate with each other by name.
- Runs
mongo:5.0image - Credentials injected via Terraform variables
- Exposed on port
27017
- Runs the Node.js web app
- Connects to MongoDB using the container name as hostname
- Exposed on port
3000 - Depends on MongoDB being healthy first
┌─────────────────────────────────┐
│ Docker (local) │
│ │
Browser │ ┌──────────┐ ┌─────────────┐ │ │ │ │ webapp │ │ mongodb │ │ │ :3000 │ │ container│──▶│ container │ │ └─────────▶│ │ │ │ │ │ │ └──────────┘ └─────────────┘ │ │ app-network │ └─────────────────────────────────┘ ▲ Provisioned by Terraform
Prerequisites: Terraform and Docker installed.
1. Clone the repo:
git clone https://github.com/umarjay/terraform-docker-infrastructure.git
cd terraform-docker-infrastructure2. Initialize Terraform (downloads Docker provider):
terraform init3. Preview what will be created:
terraform plan4. Apply — provisions the containers:
terraform applyType yes when prompted. The webapp URL will be printed when done.
5. Open in browser: http://localhost:3000
6. Destroy infrastructure when done:
terraform destroyVariables can be customized in variables.tf or passed at runtime:
terraform apply -var="webapp_port=8080"| Variable | Description | Default |
|---|---|---|
mongo_username |
MongoDB root username | myusername |
mongo_password |
MongoDB root password | mypassword |
webapp_port |
Port to expose webapp on | 3000 |
After terraform apply, the following values are displayed:
| Output | Description |
|---|---|
webapp_url |
URL to access the web app |
mongo_container_name |
Name of the MongoDB container |
webapp_container_name |
Name of the webapp container |
- Providers — Using the kreuzwerker Docker provider
- Resources — Defining containers, images and networks as code
- Variables — Parameterizing configuration for reusability
- Outputs — Surfacing useful information after deployment
- depends_on — Controlling resource creation order
- Sensitive values — Masking credentials in terminal output
- Docker daemon not running — Run
sudo systemctl start dockerbefore applying - Port already in use — Change
webapp_portvariable to another port e.g.3001 - Container already exists — Run
terraform destroythenterraform applyagain
Umar Jalal