Containerizing a Node.js App with Docker 🐳
In my learning journey, I recently deployed a simple Node.js application inside a Docker container. This hands-on experience allowed me to understand the process of containerizing an app and running it in an isolated environment. Here's a breakdown of the steps I followed:
Prerequisites: Install Visual Studio Code, Node.js, Docker, Docker Desktop.
Step 1: Create a Node app in the projects folder:
npx create-react-app testapp
cd testapp
npm start
Delete the node_modules directory as we will install it via the Dockerfile. (Note: We can install it with npm install).
Step 2: Create a Dockerfile with instructions for building the container image inside testapp:
FROM node:14
WORKDIR /myapp
COPY . .
RUN npm install
EXPOSE 3000
CMD ["npm", "start"]
Step 3: Build the Docker image from the Dockerfile:
docker build -t mywebapp:01 .
It will build the image in the current directory.
Step 4: Run the container from the built image:
Recommended by LinkedIn
docker run -d --rm --name "mywebcontainer" -p 3001:3000 mywebapp:01
This command runs the container in detached mode, removes it automatically after stopping, names it "mywebcontainer," and maps the host port 3001 to the container port 3000.
Note: We can use this image multiple times to build multiple containers because they are environment isolated.
Step 5: Verify the running container:
docker ps -a
It will show all process statuses.
Step 6: Access the app outside the container by visiting http://localhost:3001 in my browser.
Throughout this process, I learned about Docker concepts like images, containers, port mapping, and container management commands like docker ps, docker stop, docker rm, and more.
Containerizing applications is becoming increasingly important in modern software development, and Docker simplifies the process of creating, deploying, and running applications in isolated environments. This hands-on experience has deepened my understanding of containerization and has motivated me to further explore Docker and its ecosystem.