Dockerfile for a Node.js application
Create a Dockerfile for a Node.js app: Set up your environment, install dependencies, and containerize your Node.js app for smooth deployment.
Published Sep 25, 2024
you can use any text editor of your choice. Below is an example of how to create a simple Dockerfile using the
nano
text editor:- Open a terminal.
- Navigate to the directory where you want to create the Dockerfile.
- Type
nano Dockerfile
and press Enter. This will open thenano
text editor with a new file namedDockerfile
. - Enter the Dockerfile contents according to your requirements.
- Once you’re done editing, press
Ctrl + X
to exitnano
. It will prompt you to save the changes. PressY
to confirm saving, and then pressEnter
to save the file with the nameDockerfile
.
Here’s an example of a simple Dockerfile for a Node.js application:
This Dockerfile:
- Uses the official Node.js Docker image with version 14 based on Alpine Linux for a smaller image size.
- Sets the working directory inside the container to
/usr/src/app
. - Copies
package.json
andpackage-lock.json
files from the host to the container. - We run
npm install
to install dependencies defined inpackage.json
. - Copies the rest of the application source code from the host to the container.
- Exposes port 3000 to allow communication with the container.
- Sets an environment variable
NODE_ENV
to "production". - Specifies that the command to run when the container starts is
node app.js
.
After creating the Dockerfile, you can build a Docker image using the
docker build
command.Replace
my-node-app
with the desired name for your Docker image.After building the image, you can run a container from it using:
This command runs a container based on your Docker image, forwarding port 3000 from the container to port 3000 on your host machine. Adjust the port mapping as needed based on your application’s requirements.