Conclusion: Setting Up a Docker Container for a Node.jsApplication
Congratulations!
We successfully created a Docker container for a simple "Hello, World!" application by following these steps:
-
Installed Docker:
-
We ensured that Docker was installed on our system, enabling us to build and run containers.
-
-
Created a Application:
-
We wrote a simple
app.jsfile using that sets up an HTTP server and responds with "Hello, World!". -
We ensured that was installed and tested the application locally to verify it worked correctly.
-
-
Wrote a Dockerfile:
-
We crafted a Dockerfile to define the environment and steps needed to containerize our application:
-
FROM node:14: Used the official image as the base.
-
WORKDIR /app: Set the working directory inside the container.
-
COPY package.json ./*: Copied
package.jsonfiles to leverage Docker’s caching mechanism. -
RUN npm install: Installed necessary packages.
-
COPY . .: Copied the rest of the application code to the container.
-
EXPOSE 8080: Exposed port 8080 for outside access.
-
CMD ["node", "app.js"]: Defined the command to run the application.
-
-
-
Built the Docker Image:
-
We ran the command
docker build -t my-node-app .to build the Docker image and tagged it asmy-node-app.
-
-
Ran the Docker Container:
-
We executed
docker run -p 8080:8080 my-node-appto start a container from the image and mapped the container’s port 8080 to our host’s port 8080. -
We verified the application was running by visiting
http://localhost:8080/in a web browser and seeing the "Hello, World!" message.
-
By following these steps, we were able to containerize our application using Docker, making it portable and consistent across different environments. This process is fundamental in modern application development and deployment, facilitating easier management and scalability of applications.
6