Dockerize a nodejs App

Dockerize a nodejs App

creating a Docker container for a Node.js application:

  1. Start by creating a new directory for your project and navigate into it:

bash

Copy code
mkdir?my-node-app?cd?my-node-app        

  1. Create a new Node.js project and install any necessary dependencies:

bash

Copy code
npm init -y npm install express        

  1. Create a new file called app.js and add some code to create a basic HTTP server using the express module:

javascript

Copy code
const?express =?require('express');?const?app =?express(); app.get('/',?(req, res) =>?{ res.send('Hello, World!'); }); app.listen(3000,?() =>?{console.log('Server listening on port 3000'); });        

  1. Test your application by running it locally:

bash

Copy code
node app.js        

  1. Open a web browser and navigate to https://localhost:3000. You should see the message "Hello, World!".
  2. Create a new file called Dockerfile and add the following code:

bash

Copy code
# Use an official Node.js runtime as a parent image?FROM node:14-alpine# Set the working directory to /app?WORKDIR /app?# Copy the current directory contents into the container at /app?COPY . /app?# Install any necessary dependencies?RUN npm install?# Make port 3000 available to the world outside this container?EXPOSE 3000?# Define the command to run your app when the container starts?CMD [?"node",?"app.js"?]        

  1. This Dockerfile tells Docker to start from an official Node.js runtime image, set the working directory to /app, copy the current directory's contents into the container, install any dependencies, expose port 3000, and finally run the app.js script using the node command.
  2. Build your Docker image using the docker build command:

bash

Copy code
docker build -t my-node-app .        

  1. This command builds an image called my-node-app using the . as the build context.
  2. Run your Docker container using the docker run command:

bash

Copy code
docker run -p 3000:3000 my-node-app        

  1. This command starts a container based on the my-node-app image and maps port 3000 in the container to port 3000 on your local machine.
  2. Open a web browser and navigate to https://localhost:3000. You should see the message "Hello, World!" served from the Docker container.

Congratulations! You've just created a Docker container for a Node.js application.


#docker #dockercontainer #nodejs #microservice

要查看或添加评论,请登录

Anil Bidari的更多文章

社区洞察

其他会员也浏览了