How do I deploy a Python Docker image on AWS EC2 with TypeScript?
In this guide, we will deploy a Python Docker image on an AWS EC2 instance using Pulumi with TypeScript. We will create an EC2 instance, install Docker, and run a Python Docker container.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Create a new security group for the EC2 instance
const securityGroup = new aws.ec2.SecurityGroup("web-secgrp", {
description: "Enable HTTP access",
ingress: [
{ protocol: "tcp", fromPort: 80, toPort: 80, cidrBlocks: ["0.0.0.0/0"] },
{ protocol: "tcp", fromPort: 22, toPort: 22, cidrBlocks: ["0.0.0.0/0"] },
],
});
// Create a new EC2 instance
const server = new aws.ec2.Instance("web-server", {
instanceType: "t2.micro",
securityGroups: [securityGroup.name], // Reference the security group
ami: "ami-0c55b159cbfafe1f0", // Amazon Linux 2 AMI
userData: `#!/bin/bash
# Install Docker
sudo yum update -y
sudo amazon-linux-extras install docker -y
sudo service docker start
sudo usermod -a -G docker ec2-user
# Run a Python Docker container
sudo docker run -d -p 80:80 python:3.8-slim python -m http.server 80
`,
});
// Export the public IP of the instance
export const publicIp = server.publicIp;
export const publicHostName = server.publicDns;
Key Points
- Security Group: Defines the rules for inbound traffic to the EC2 instance, allowing HTTP and SSH access.
- EC2 Instance: Creates an Amazon Linux 2 EC2 instance with Docker installed.
- User Data: Script to install Docker, start the Docker service, and run a Python Docker container serving on port 80.
- Exports: Outputs the public IP and DNS of the EC2 instance.
Summary
We created an AWS EC2 instance using Pulumi and TypeScript, configured it to run Docker, and deployed a Python Docker container. This setup allows the Python application to be accessible via the instance’s public IP.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.