Deploying a containerized node app to AWS

JULY 15, 2023  ·  338 WORDS

I've mainly worked as a product engineer but on occassions I've had to modifiy Dockerfile and kubeconfig files. The keyword there is 'modify'. Everything was already setup by some awesome infra engineers and for the work I had to do, I told them exactly what I needed and they provided detailed instructions on how to get it done and reviewed all of my PR changes. It is a bit embarrassing to admit that I've never containerized and deployed an app from scratch before.

In this article, I hope to provide a guide that would anyone to deploy a simple node application to AWS as a dockerized container. Let's start with setting up the node application with:

npm init -y
npm i express

In the app folder, create an index.js file and add the following code to it:

1const express = require("express");
2const app = express();
3
4const port = process.env.PORT || 8000;
5
6app.get("/ping", (req, res) => {
7 res.send("pong");
8});
9
10app.listen(port, () => {
11 console.log(`Server is running on port ${port}`);
12});

Once the app is deployed, when a GET /ping request is made, the server will respond with 'pong'

You can install something like 'nodemon' to reload builds

To deploy this app to AWS, we will first need to set it up to run in a container. Docker is a popular option so let's go with that.

# Use the official Node.js base image
FROM node:14
# Set the working directory inside the container
WORKDIR /app
# Copy package.json and package-lock.json to the working directory
COPY package*.json ./
# Install app dependencies
RUN npm install --production
# Copy the app's source code to the working directory
COPY . .
# Expose the port that the app will run on
EXPOSE 8000
# Start the app
CMD ["node", "index.js"]

You can confirm that this is working on Postman. A question may arise then, why do we need this extra boilerplate. Why not just run the app directly? With so many dependencies, there are a lot of possible situations where the problem could be "it works on my machine". Now how do you actually deploy this to AWS?