In this blog, we are going to go through this process
We will create a file named Dockerfile and open it in terminal . We are using vim to edit it.
1.First we will import node 18-alpine
You can see the latest version of node from here : https://hub.docker.com/_/node
So, lets import the node image and tag: 18-alpine . Alpine is a very light distribution.
We will expose port 3000 for this app. Assume it as an instruction
Now, we will use alpine package manage to install
RUN apk add --uppdate tini
We will also create directory to copy usr/src/app using
RUN mkdir -p usr/src/app
and then go into it using
WORKDIR usr/src/app
4.Node uses a package manager and thus we will create a package.json file and copy it to the package.json file.
Then we will install dependencies using
RUN npm install
Also we will keep it small and clean thus
RUN npm cache clean
or, in short use
RUN npm install && npm cache clean
- We will then copy everything from the current node:18-alpine using
COPY ..
- Now we need to start the container using 'tini -- node ./bin/www'
We will use the json format to add this
CMD ["tini","--","node","./bin/www"]
Now, save this file and go to terminal. We will build the dockerfile using this command
docker build -t <random image name you wish> .
"." is given to build it in the current directory
What happened?
Lets see the images
You may see an image with tag
As the problem occured, we faced this issue. We will solve this by making a simple change in our docker file
RUN npm install && npm cache clean --force
We will force this line to be implemented and to clear our doubts, we will now create a new image with a new name called "testimage"
This time it worked perfectly and added the latest tag.
Now, look at the images
we can see our image on top with latest tag.
So, image is created! Congratulations!
Now, lets create a container using this image
docker container run -rm -p 80:3000 --name test_container testimage
-rm is used when we want to stop the container till the moment we exit the container.
-p 80:3000 is used because it will run on 80 but listens from 3000 . Also, we exposed 3000 for that in our Dockerfile
We also have set a container name to our our container and used the image "testimage"
Now go to your web browser and type "localhost", you can see this
Go to your terminal and you will see this logs
Now press control+ C to stop it .
Now lets put this image uploaded to our Dockerhub id with a new name
docker tag testimage <dockerhub username/new image name>
Now, lets push it
using
docker push <docker hub username/image name>
Go to your dockerhub and see the image there
Congratulations! You have completed it
If you get stuck, you can see our final Dockerfile
From node:18-alpine
EXPOSE 3000
RUN apk add --update tini
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json package.json
RUN npm install && npm cache clean --force
COPY . .
CMD ["tini","--","node","./bin/www"]
See you again