في المقدمة Dockerfileبعد أن قدمت مثالًا بسيطًا لملف Node.js Docker:
FROM node:14 WORKDIR /usr/src/app COPY package*.json app.js ./ RUN npm install EXPOSE 3000 CMD ["node", "app.js"]
NOTE: use double quotes in the
CMDline. Single quotes will result in an error.
I’m going to create this file in the
dev/docker/examplenodefolder. I create a simple Node.js app in the
app.jsfile, using Express:
const express = require('express') const app = express()
app.get(’/’, (req, res) => res.send(‘Hello World!’)) app.listen(3000, () => console.log(‘Server ready’))
Super simple, but we have one dependency. I need to add it to the
package.jsonfile, so I run
npm init -y npm install express
Now you can run
node app.jsand make sure it works:
Stop this process and let’s create a Docker Image from this.
All you need are the
And the Dockerfile. Create a
Dockerfilefile in the same folder, with no extension (not Dockerfile.txt).
You can freely delete the
node_modulesfolder that now contains the Express library and its dependencies, but you can also create a
.dockerignorefile and add
node_modulesinside it, to make Docker ignore this folder completely.
It works like
Run the command
docker build -t examplenode .
It will take a while to download the Node image and run
npm install, then you’ll get a successful message.
It’s important to note that after you first download a base image like the
nodeone we use here, that will be cached locally, so you don’t need to download it again and the image building process will be much faster.
Now we can run a container from the image:
docker run -d -p 3000:3000 --name node-app examplenode
Now you can see the image running in Docker Desktop:
And you can click the “Open in browser” button to open the app running on port 3000:
Just like before! Except now the app is running in its own container, completely isolated, and we can run whatever version of Node we want in the container, with all the benefits Docker gives us.
For example you can remove the container and run it on port 80 instead of 3000, with:
docker run -d -p 80:3000 --name node-app examplenode
The image does not need to change, all you change is the port mapping. Here’s the result:
More docker tutorials:
- Introduction to Docker
- Introduction to Docker Images
- Introduction to Docker Containers
- Installing Docker on macOS
- First steps with Docker after the installation
- Using Docker Desktop to manage a Container
- Create a simple Node.js Hello World Docker Container from scratch
- What to do if a Docker container immediately exits
- Working with Docker Containers from the command line
- Working with Docker Images from the command line
- Sharing Docker Images on Docker Hub
- How to access files outside a Docker container
- How to commit changes to a Docker image
- Updating a deployed container based on a Docker image