In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/02 Report--
This article will not explain the use and installation of Docker commands, because the previous article taught you how to get started with Docker. In practice, it has also been explained in detail. If you are not clear, you can click on the link to look back. This article focuses on how to implement Docker containerization and some practical optimization of Node.js project, as well as some common problems. Of course, if there are any other questions on the use, you are welcome to add comments in the comments area.
Brief introduction of the author: may Jun, Nodejs Developer, post-90s youth who love technology and like to share, official account "Nodejs technology stack", Github open source project www.nodejs.red
What can you learn from this article?
Learn how to use Docker containment a Node.js service dynamically set environment variables a Dockerfile file to build different versions of Node.js private NPM package how to authenticate Egg.js framework Docker containerization should pay attention to the optimization of Docker image volume and construction time
Docker into a Node.js application
At the beginning of this article, we first create a simple Node.js application, then create a Docker image for the application, and build and run it.
Create a Node.js project
First we need to create an app.js to start a HTTP service, and then we will run the program with the help of Docker
Const http = require ('http'); const PORT = 30010 res.end Const server = http.createServer ((req, res) = > {res.end (' Hello Docker');}) server.listen (PORT, () = > {console.log ('Running on and PORT,' NODE_ENV', process.env.NODE_ENV);})
Then we create a package.json file, which describes your application and the dependencies you need, which should be familiar to students who have written Node.js. Here, I added npm run dev and npm run pro commands to scripts, because I want to introduce how to pass parameters in the build time to set environment variables dynamically.
{"name": "hello-docker", "version": "1.0.2", "description": "", "author": "May", "main": "app.js", "scripts": {"dev": "NODE_ENV=dev node app.js", "pro": "NODE_ENV=pro node app.js"}}
Dockerfile file
This is the information contained in a Dockerfile file, and these commands are also explained in the introduction and practice of Docker.
FROM node:10.0-alpineRUN apk-- update add tzdata\ & & cp / usr/share/zoneinfo/Asia/Shanghai / etc/localtime\ & & echo "Asia/Shanghai" > / etc/timezone\ & & apk del tzdataRUN mkdir-p / usr/src/nodejs/WORKDIR / usr/src/nodejs/# add npm packageCOPY package.json / usr/src/nodejs/package.jsonRUN cd / usr/src/nodejs/RUN npm i# copy codeCOPY. / usr/src/nodejs/EXPOSE 30010CMD npm run dev
Create a .dockerkeeper file under the sibling file of Dockerfile to avoid putting your local debug files, node_modules, and other files into the Docker container
.gitnode _ modulesnpm-debug.log
At this point, you can build a Docker image with the following command
$docker image build-t mayjun/hello-docker
Then through the docker run-d-p 30010 mayjun/hello-docker command to run a Docker container, but there is a doubt that I have production and testing, according to the above CMD npm run dev can only package a kind of environment, of course, you can also build a file to achieve or some other methods.
Set environment variables dynamically
In order to solve the above doubt, my idea is to dynamically set environment variables by passing parameters during image construction, and make changes to the Dockerfile file. See the following implementation:
EXPOSE 30010ARG node_env # newly added ENV NODE_ENV=$node_env # newly added CMD npm run ${NODE_ENV} # modified
Let's explain the above code.
A variable is defined by the ARG directive, which you can pass to the builder ARG node_env by using the docker build command of the-- build-arg = flag to refer to the variable ENV NODE_ENV=$node_env in Dockerfile using CMD npm run ${NODE_ENV}.
All that's left is to dynamically pass in the parameters when building the image.
$docker image build--build-arg node_env=dev-t mayjun/hello-docker:1.0.2. # build a test environment $docker image build--build-arg node_env=pro-t mayjun/hello-docker:1.0.2. # build a production environment
Run the container
$docker run-d-p 30010 npm run 30010 mayjun/hello-docker:1.0.2$ docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES2bc6e62cd0e8 mayjun/hello-docker:1.0.2 "/ bin/sh-c 'npm run …" 3 minutes ago Up 3 minutes 0.0.0.0 docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES2bc6e62cd0e8 mayjun/hello-docker:1.0.2-> 30010/tcp elastic_bouman
View container log
Docker logs-f 2bc6e62cd0e8 > hello-docker@1.0.0 dev / usr/src/nodejs > NODE_ENV=dev node app.jsRunning on http://localhost: 30010 NODE_ENV dev
I have packaged the above code into an image mayjun/hello-docker:1.0.2, which can be pulled to view docker pull mayjun/hello-docker:1.0.2.
Private NPM packages for Docker and Node.js
If you use a private NPM package in your project, there will be an error installing npm private package 404 in the process of building an image in Dcoker. If it is outside the container, we can log in to an account with NPM private package permission to solve this problem, but we cannot do so in Docker.
Create an authentication token
In order to install the private package, we need to "create an authentication token" to access our private NPM package in the continuous integration environment and within the Docker container. Please refer to https://docs.npmjs.com/creating-and-viewing-authentication-tokens for more information on how to create the private NPM package.
Realization method
We need to add the following two commands during the creation of the Dockerfile file:
# 528das62mure03eMub 4dc2murba67 * this Token is the authentication token tokenRUN echo "/ / registry.npmjs.org/:_authToken=528das62-e03e-4dc2-ba67-*" > / root/.npmrcRUN cat / root/.npmrc created for you.
Docker containerization of Egg framework
In Egg, if it is egg-scripts start-- daemon, remove-- daemon and egg-scripts start directly, otherwise the Docker container will fail to start.
Take a look at the following code example. You can modify package.json. The Dockerfile file is the same as the first Docker Node.js application above.
Package.json
{"scripts": {"start": "egg-scripts start" / / remove-- daemon}}
You can also refer to Egg Issues "docker container cannot be run up, have you encountered it?" Https://github.com/eggjs/egg/issues/1543
Optimization of Docker Image Volume and Construction time
If a mirror image is usually very large without optimization, here are some optimizations made in practice.
RUN/COPY layering
Each instruction in Dockerfile creates a mirror layer, and each mirror layer can be reused and cached without modification or modification of the Dockerfile instruction or copied project file.
The following code can be found in the mayjun/hello-docker:latest image warehouse. In the following example, the NPM module will be reinstalled after the source code has been changed, regardless of whether the package.json has been changed or not, which is obviously not good, so we need to improve it below.
#... WORKDIR / usr/src/nodejs/hello-dockerCOPY. / usr/src/nodejs/hello-dockerRUN npm install#...
The improved code is shown below. We let package.json advance so that the NPM package will not be reinstalled without modification of package.json, and the deployment time will be reduced.
#... WORKDIR / usr/src/nodejs/# add npm packageCOPY package.json / usr/src/app/package.jsonRUN cd / usr/src/app/RUN npm i# copy codeCOPY. / usr/src/app/#...
Node.js Alpine image optimization
The image of mayjun/hello-docker:1.0.0 can also be searched in the Docker repository, around 688MB before optimization.
$docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEmayjun/hello-docker 1.0.0 7217fb3e9daa 5 seconds ago 688MB
Optimize with Alpine
Alpine is a very small Linux distribution. It is also the easiest to choose the Alpine version of Node.js if you want to greatly reduce the image size. In addition, the time zone of-alpine is not domestic by default, and Dockerfile is required to configure the time zone.
FROM node:10.0-alpineRUN apk-- update add tzdata\ & & cp / usr/share/zoneinfo/Asia/Shanghai / etc/localtime\ & & echo "Asia/Shanghai" > / etc/timezone\ & & apk del tzdataRUN echo "Asia/Shanghai" > / etc/timezoneRUN mkdir-p / usr/src/nodejs/WORKDIR / usr/src/nodejs/# add npm packageCOPY package.json / usr/src/app/package.jsonRUN cd / usr/src/app/RUN npm i# copy codeCOPY. / usr/src/app/EXPOSE 30010CMD npm start
When you repackage a version of mayjun/hello-docker:1.1.0 and check the effect again, you can see that the image file has been reduced from 688MB to 85.3MB. This volume optimization is still very large.
$docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEmayjun/hello-docker 1.1.0 169e05b8197d 3 minutes ago 85.3MB
Do not pack devDependencies packages in production environment
Some packages used in the test environment are not included when mirroring in the production environment, that is, the package.json file devDependencies object is filtered by specifying the-- production parameter after npm I
The improvements are as follows:
FROM node:10.0-alpine# omitted. # add npm packageCOPY package.json / usr/src/app/package.jsonRUN cd / usr/src/app/RUN npm I-- production # changed here # omitted.
Repackage a version of mayjun/hello-docker:1.2.0 and check the effect again. You can see that the image files have been reduced from 85.3MB to 72.3MB.
$docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEmayjun/hello-docker 1.2.0 f018aa578711 3 seconds ago 72.3MB
common problem
Question1
The following command reports the following error when deleting an image:
$docker rmi 6b1c2775591eError response from daemon: conflict: unable to delete 6b1c2775591e (must be forced)-image is referenced in multiple repositories
If you are careful, you may find that the image ID 6b1c2775591e points to both hello-docker and mayjun/hello-docker repositories, which is why the deletion failed.
$docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEmysql 5.7 383867b75fd2 6 days ago 373MBhello-docker latest 6b1c2775591e 7 days ago 675MBmayjun/hello-docker latest 6b1c2775591e 7 days ago 675MB
Specify repository and tag to delete. After executing the delete command, check the mayjun/hello-docker warehouse again and it will be gone.
$docker rmi mayjun/hello-docker$ docker images REPOSITORY TAG IMAGE ID CREATED SIZEmysql 5.7 383867b75fd2 6 days ago 373MBhello-docker latest 6b1c2775591e 7 days ago 675MB
Question2
Execute the delete image command to report the following error:
$docker rmi 9be467fd1285Error response from daemon: conflict: unable to delete 9be467fd1285 (cannot be forced)-image is being used by running container 1febfb05b850
According to the prompt, there is a container that is running. You need to stop the container first, delete the container and then delete the image.
$docker container kill 1febfb05b850 # stop the container $docker rm 1febfb05b850 # delete the container $docker rmi 9be467fd1285 # Delete the image
Question3
The set working directory (WORKDIR) should be consistent with the following
... WORKDIR / usr/src/nodejs/# add npm packageCOPY package.json / usr/src/node/package.json # directory inconsistent RUN cd / usr/src/node/ # directory inconsistent RUN npm I...
For example, in the above configuration, the following error will be reported because the working directory is not consistent with the actual COPY directory:
Then change it to be consistent as follows
... WORKDIR / usr/src/nodejs/# add npm packageCOPY package.json / usr/src/nodejs/package.json # changed to consistent RUN cd / usr/src/nodejs/# changed to consistent RUN npm I...
The above is the whole content of this article, I hope it will be helpful to your study, and I also hope that you will support it.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.