Port mapping for containerized applications.
TypeScriptIn Pulumi, port mapping for containerized applications can usually be achieved through the use of container and networking resources provided by cloud providers or by Docker itself. To demonstrate this, let's walk through an example of setting up a basic containerized application with port mapping using Pulumi with Docker as the container runtime.
The resources we'll use from Pulumi are:
docker.Network
: This resource is used to create a network that our containers can communicate on.docker.Container
: This resource allows us to define and run a Docker container, including specifying port mappings.
To understand the code, let's break it down step by step:
- We create a new Docker network. Containers on the same network can communicate with each other using internal ports without exposing them to the host.
- We define a Docker container and specify the port mappings. This allows the container to receive traffic from the host on a specified port and forward it to a port inside the container.
Here is a TypeScript program that demonstrates how you would set up a container with port mapping using Pulumi:
import * as pulumi from '@pulumi/pulumi'; import * as docker from '@pulumi/docker'; // Create a custom Docker network const network = new docker.Network("app-network", { name: "app-network", // Additional network configurations can go here }); // Define a Docker container with port mapping const appContainer = new docker.Container("app-container", { name: "my-app-container", image: "nginx", // Example image networksAdvanced: [{ name: network.name, }], ports: [{ internal: 80, // Port inside the container external: 8080 // Port exposed on the host }], // More container configurations can go here, such as environment variables, volumes, etc. }); // Export the container's name and network ID export const containerName = appContainer.name; export const networkId = network.id;
In this example, we are creating an Nginx container that listens on internal port 80. We've used port mapping to make Nginx accessible on port 8080 of the host machine. This is just an illustrative example; in a real-world scenario, you would replace
"nginx"
with the name of your image and configure the container according to your application's requirements, such as environment variables, command, volumes, and so forth.This program defines the necessary Docker resources with Pulumi, and once applied, it would set up your containerized application with the specified port mappings.
To run this program, you would use the Pulumi CLI to execute the following steps:
pulumi up
: This command creates or updates the resources in accordance with the Pulumi program.pulumi stack output
: After a successfulup
, this command can be used to view the exported outputs, such as the container name and network ID in this case.
Using the Pulumi CLI, along with your Pulumi program, you can manage all aspects of your infrastructure as code.