This will be your last Dockerfile for all of tour NodeJs applications.
( A summary this article is available in here also )
Introduction to Docker and Dockerfiles
Docker has revolutionized the way we develop and deploy applications by enabling containerization. Dockerfiles are the blueprints that define the steps to create container images, encapsulating the application and its dependencies. However, single-stage Dockerfiles, while simple, can lead to inefficiencies, particularly for Node.js applications. Multi-stage Dockerfiles offer a solution, providing several advantages in terms of image size, security, and build times.
What are the stages in multi stage Dockerfile ?
- development: install all the dependencies
- build: prepares the application for production with optimized bundle size
- production: sets up the production environment
Understanding Multi-Stage Dockerfiles
A multi-stage Dockerfile consists of multiple stages, each serving a specific purpose. Unlike single-stage Dockerfiles that combine all steps into a single image, multi-stage builds separate the build environment from the final runtime environment. This separation leads to several benefits
Benefits of Multi-Stage Dockerfiles
- Reduced Image Size: By keeping the build environment (with all its dependencies) out of the final image, multi-stage builds significantly reduce the image size. This translates to faster downloads, deployments, and smaller storage requirements.
- Improved Security: Only the necessary application files and dependencies are present in the final runtime image, minimizing the attack surface and potential vulnerabilities.
- Faster Build Times: Caching intermediate build stages can significantly speed up subsequent builds, especially when dependencies have been downloaded and installed previously.
Creating a Multi-Stage Dockerfile for Node.js
Here’s a breakdown of creating a multi-stage Dockerfile for a Node.js application:
Development Stage
FROM node:20-alpine AS development
WORKDIR /usr/src/app
COPY --chown=node:node package*.json ./
RUN npm ci -f
COPY --chown=node:node . .
USER node
Explanation
- This stage sets up the development environment.
- It uses a lightweight Node.js image (
20-alpine
variant) from a public container registry. - Sets the working directory to
/usr/src/app
. - Copies
package.json
andpackage-lock.json
(oryarn.lock
) to install dependencies efficiently usingnpm ci
. - Copies the application code into the container.
- Switches to a non-root user
node
for security reasons.
Build for Production Stage
FROM node:20-alpine AS build
WORKDIR /usr/src/app
COPY --chown=node:node package*.json ./
COPY --chown=node:node --from=development /usr/src/app/node_modules ./node_modules
COPY --chown=node:node . .
RUN npm run build
RUN npm ci -f --only=production && npm cache clean --force
USER node
Explanation
- This stage prepares the application for production deployment.
- It starts from the same Node.js image as the development stage.
- Copies
package.json
to install production dependencies. - Utilizes the
node_modules
directory generated during the development stage, saving time and resources by avoiding redundant dependency installations. - Copies the application code.
- Builds the application using the specified build command (
npm run build
). - Installs only production dependencies using
npm ci
and cleans the npm cache.
Production Stage
FROM node:20-alpine AS production
ENV NODE_ENV production
COPY --chown=node:node --from=build /usr/src/app/node_modules ./node_modules
COPY --chown=node:node --from=build /usr/src/app/dist ./dist
CMD [ "node", "dist/main.js" ]
Explanation
- This stage sets up the production environment.
- Starts from the same Node.js image.
- Copies the production dependencies and the built application (
dist
directory) from the build stage. - Specifies the command to run the application (
node dist/main.js
) as the default command when the container starts.
Complete Dockerfile
FROM node:20-alpine AS development
WORKDIR /usr/src/app
COPY --chown=node:node package*.json ./
RUN npm ci -f
COPY --chown=node:node . .
USER node
FROM node:20-alpine AS build
WORKDIR /usr/src/app
COPY --chown=node:node package*.json ./
COPY --chown=node:node --from=development /usr/src/app/node_modules ./node_modules
COPY --chown=node:node . .
RUN npm run build
RUN npm ci -f --only=production && npm cache clean --force
USER node
FROM node:20-alpine AS production
ENV NODE_ENV production
COPY --chown=node:node --from=build /usr/src/app/node_modules ./node_modules
COPY --chown=node:node --from=build /usr/src/app/dist ./dist
CMD [ "node", "dist/main.js" ]
Best Practices for Multi-Stage Dockerfiles
- Caching: Leverage Docker’s caching mechanism to optimize build times by caching intermediate stages.
- Multi-line Commands: Use continuation characters (
\
) or escape characters (\"
) for multi-line commands within Dockerfile instructions. - Environment Variables: Manage environment variables for different stages or throughout the build process using
ENV
instructions. - Multi-arch Builds: Consider building multi-architecture images for different CPU architectures using the
BUILD
instruction and the--platform
flag
Common Challenges and Troubleshooting
- Identifying Build Issues: Use
docker build -t <image-name>:<tag> -v .:/app --no-cache .
to identify build errors and troubleshoot issues. - Image Size Optimization:
- Analyze image size using
docker image inspect
anddu -sh
. - Consider further strategies like multi-arch builds, removing unnecessary files, and using smaller base images.
- Analyze image size using
Conclusion
This Dockerfile is structured to facilitate the development, build, and deployment of a NestJS aMulti-stage Dockerfiles offer a powerful approach to optimizing Node.js application deployments. By embracing this technique, you can achieve significant reductions in image size, improve security, and streamline your build processes. Experiment with multi-stage Dockerfiles in your projects to unlock these benefits and enhance your development workflow. Start by implementing the steps and best practices outlined above, and explore further resources to delve deeper into advanced multi-stage build techniques.
References
Multi-stage builds
Learn about multi-stage builds and how you can use them to improve your builds and get smaller imagesdocs.docker.com
I do accept as true with all the concepts you’ve presented for your post. They’re very convincing and will certainly work. Nonetheless, the posts are very brief for starters. May just you please extend them a little from subsequent time? Thanks for the post.
I truly appreciate your work, Great post.
Keep working ,impressive job!
Some truly interesting points you have written.Aided me a lot, just what I was looking for : D.
Thanks for all of your work on this website. My aunt really loves getting into internet research and it’s really easy to see why. I notice all about the lively way you produce valuable items through your website and even welcome participation from the others on this point and our own child has been starting to learn a great deal. Take advantage of the remaining portion of the new year. Your performing a dazzling job.
Simply wanna remark that you have a very decent site, I like the design and style it really stands out.
You could definitely see your skills in the paintings you write. The world hopes for even more passionate writers such as you who aren’t afraid to mention how they believe. Always follow your heart. “Man is the measure of all things.” by Protagoras.
Hi there are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any html coding knowledge to make your own blog? Any help would be really appreciated!
It is the best time to make some plans for the future and it’s time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or advice. Perhaps you can write next articles referring to this article. I desire to read more things about it!
I have recently started a blog, the information you offer on this site has helped me greatly. Thanks for all of your time & work.
I’m truly enjoying the design and layout of your blog. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Fantastic work!
Keep functioning ,fantastic job!
Thanks for another informative site. Where else could I get that type of info written in such a perfect way? I’ve a project that I am just now working on, and I have been on the look out for such info.
Excellent site. A lot of useful information here. I’m sending it to several friends ans also sharing in delicious. And of course, thanks for your effort!
This is the right blog for anyone who wants to find out about this topic. You realize so much its almost hard to argue with you (not that I actually would want…HaHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, just great!
It’s a shame you don’t have a donate button! I’d certainly donate to this excellent blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to new updates and will share this blog with my Facebook group. Talk soon!
Spot on with this write-up, I really assume this website wants far more consideration. I’ll in all probability be once more to learn much more, thanks for that info.
Greetings! I know this is kind of off topic but I was wondering which blog platform are you using for this website? I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at options for another platform. I would be awesome if you could point me in the direction of a good platform.
Thank you for any other wonderful post. The place else may anybody get that kind of information in such a perfect means of writing? I’ve a presentation subsequent week, and I’m at the look for such information.
I’m truly enjoying the design and layout of your website. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Great work!
Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across. It extremely helps make reading your blog significantly easier.
I know this if off topic but I’m looking into starting my own weblog and was curious what all is required to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet smart so I’m not 100 sure. Any tips or advice would be greatly appreciated. Many thanks
This is very interesting, You are a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your wonderful post. Also, I’ve shared your web site in my social networks!
Simply want to say your article is as surprising. The clarity in your post is just spectacular and i could assume you are an expert on this subject. Fine with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please continue the rewarding work.
I think you have remarked some very interesting points, regards for the post.
Does your website have a contact page? I’m having a tough time locating it but, I’d like to shoot you an email. I’ve got some suggestions for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it develop over time.
What i do not understood is if truth be told how you are no longer really a lot more well-liked than you may be right now. You’re so intelligent. You recognize thus considerably relating to this topic, produced me in my view consider it from numerous various angles. Its like women and men are not involved except it¦s something to do with Woman gaga! Your individual stuffs excellent. Always take care of it up!
I truly appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thank you again!
I’ve been surfing on-line more than 3 hours lately, but I by no means found any attention-grabbing article like yours. It¦s pretty price enough for me. In my view, if all webmasters and bloggers made good content as you did, the web can be much more useful than ever before.
There is noticeably a bunch to identify about this. I consider you made some good points in features also.
so much good info on here, : D.
You have brought up a very excellent points, appreciate it for the post.
Wow, superb blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is great, as well as the content!
There are some fascinating points in time in this article but I don’t know if I see all of them middle to heart. There may be some validity however I will take hold opinion till I look into it further. Good article , thanks and we would like more! Added to FeedBurner as properly
I love reading through and I conceive this website got some genuinely utilitarian stuff on it! .
I have learn some good stuff here. Certainly value bookmarking for revisiting. I surprise how much effort you set to make this type of great informative website.
I’d should test with you here. Which isn’t one thing I often do! I enjoy studying a post that may make individuals think. Also, thanks for permitting me to remark!
Lovely site! I am loving it!! Will be back later to read some more. I am bookmarking your feeds also.
Very nice post and straight to the point. I don’t know if this is in fact the best place to ask but do you guys have any thoughts on where to hire some professional writers? Thx 🙂
This is a very good tips especially to those new to blogosphere, brief and accurate information… Thanks for sharing this one. A must read article.
Fantastic beat ! I would like to apprentice while you amend your web site, how could i subscribe for a blog site? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast offered bright clear concept
I have learn a few just right stuff here. Definitely value bookmarking for revisiting. I surprise how a lot effort you put to create the sort of wonderful informative web site.
Wow, fantastic blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is great, as well as the content!
Unquestionably believe that which you stated. Your favorite reason appeared to be on the net the easiest thing to be aware of. I say to you, I definitely get annoyed while people think about worries that they just do not know about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks
Howdy would you mind sharing which blog platform you’re using? I’m planning to start my own blog in the near future but I’m having a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique. P.S Apologies for getting off-topic but I had to ask!
Excellent read, I just passed this onto a colleague who was doing some research on that. And he actually bought me lunch because I found it for him smile So let me rephrase that: Thank you for lunch!
This is the right blog for anyone who wants to find out about this topic. You realize so much its almost hard to argue with you (not that I actually would want…HaHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, just great!
You are my aspiration, I have few web logs and very sporadically run out from to post .
Hi, Neat post. There is a problem together with your website in web explorer, could test this?K IE nonetheless is the market chief and a large component to people will omit your wonderful writing due to this problem.
Regards for all your efforts that you have put in this. very interesting information.
I precisely wished to thank you very much once more. I am not sure the things that I would have undertaken in the absence of these tricks shared by you relating to such concern. Certainly was an absolute difficult matter in my circumstances, but understanding this professional approach you solved it forced me to cry with fulfillment. I will be grateful for your advice and thus pray you know what a powerful job you are always accomplishing instructing men and women via your blog. Most likely you’ve never got to know all of us.
Hiya, I’m really glad I’ve found this info. Nowadays bloggers publish just about gossips and web and this is really annoying. A good website with interesting content, that’s what I need. Thanks for keeping this site, I’ll be visiting it. Do you do newsletters? Can’t find it.
I’ve been browsing on-line more than 3 hours nowadays, yet I by no means discovered any interesting article like yours. It’s lovely price sufficient for me. In my view, if all site owners and bloggers made excellent content as you did, the web will likely be much more useful than ever before.
Hi there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!
Wohh precisely what I was searching for, regards for posting.
Pretty nice post. I simply stumbled upon your weblog and wished to say that I have truly loved surfing around your blog posts. In any case I’ll be subscribing for your feed and I hope you write once more soon!
You are my inspiration , I have few web logs and infrequently run out from to brand : (.
Hey, you used to write great, but the last several posts have been kinda boringK I miss your super writings. Past few posts are just a bit out of track! come on!
Some times its a pain in the ass to read what blog owners wrote but this internet site is really user pleasant! .
fantastic points altogether, you just gained a new reader. What would you recommend in regards to your post that you made some days ago? Any positive?
https://1xbetnplogin.com/
What’s Going down i am new to this, I stumbled upon this I have discovered It positively helpful and it has aided me out loads. I hope to contribute & assist different customers like its helped me. Great job.
Good V I should definitely pronounce, impressed with your web site. I had no trouble navigating through all tabs and related information ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or something, web site theme . a tones way for your customer to communicate. Excellent task..
Hi there, simply become alert to your weblog through Google, and found that it’s truly informative. I am going to watch out for brussels. I will appreciate in the event you continue this in future. Many other folks might be benefited from your writing. Cheers!
whoah this blog is great i love reading your articles. Keep up the great work! You know, many people are hunting around for this info, you could aid them greatly.
Good post. I study something more difficult on completely different blogs everyday. It is going to at all times be stimulating to learn content material from other writers and observe a little something from their store. I’d desire to use some with the content material on my weblog whether you don’t mind. Natually I’ll provide you with a hyperlink in your net blog. Thanks for sharing.
Thanks on your marvelous posting! I certainly enjoyed reading it, you may be a great author.I will remember to bookmark your blog and will eventually come back sometime soon. I want to encourage continue your great job, have a nice morning!
https://1xbetvnlogin.com/
Thank you, I’ve recently been looking for info about this subject for ages and yours is the best I’ve discovered till now. But, what about the conclusion? Are you sure about the source?
My developer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using WordPress on numerous websites for about a year and am nervous about switching to another platform. I have heard good things about blogengine.net. Is there a way I can transfer all my wordpress content into it? Any help would be greatly appreciated!
Thanks for helping out, fantastic info. “Whoever obeys the gods, to him they particularly listen.” by Homer.
I don’t even know the way I stopped up here, but I believed this submit was great. I don’t understand who you might be however certainly you are going to a famous blogger in case you are not already 😉 Cheers!
Hello. excellent job. I did not imagine this. This is a remarkable story. Thanks!
I got what you intend,saved to bookmarks, very decent site.
Super-Duper blog! I am loving it!! Will come back again. I am taking your feeds also
Howdy, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of spam responses? If so how do you protect against it, any plugin or anything you can suggest? I get so much lately it’s driving me mad so any assistance is very much appreciated.
Wow, incredible weblog format! How lengthy have you ever been running a blog for? you make running a blog glance easy. The entire glance of your site is excellent, as neatly as the content material!
I was curious if you ever thought of changing the structure of your site? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or two images. Maybe you could space it out better?