In this tutorial we explain how to make a docker image and then push to docker hub so that others can pull the image and make docker containers based on the image.
For making a docker image we need to have a Dockerfile file. As an example, you have a simple nodejs application and you want to make a docker image of the application. As you know for running your application you will need a VM or machine which has nodejs installed. You need to copy your nodejs program (as for example index.js) to that machine and run the command: node index.js
To make a docker image for above example we need to first specify which operating system we need that has the nodejs installed. Then we will copy our index.js application and run the command: node index.js
In my application folder I have these files:
index.js, package.json and Dockerfile
So below is the Dockerfile:
*********************Dockerfile: FROM node:alpine WORKDIR '/app' COPY package.json . RUN npm install COPY . . CMD ["npm","start"]
****************************
As you can see in the Dockerfile we specify a basic image which has for the nodejs installed. Then we say that inside future docker container which gets created off our new image the working directory is “/app”.
Then we copy package.json and run the npm install to download the dependencies and copy the index.js file (. means everything) and the initial command is: npm start.
The package.json is :
****************************package.json
{ "dependencies": { "express": "*" }, "scripts": { "start": "node index.js" } }
****************************
and index.js is a simple express node which prints hello world when you run “node index.js” and browse http://localhost:8081/:
*************index.js:
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('hello world'); });
app.listen(8081, () => { console.log('listening on port 8081'); });
**************
Okay, now for making docker image we need to build the Dockerfile by running command below:
docker build .
the above command makes the image, but if you want to make an image with a name (example: myimage) you can run:
docker build -t myimage .
If you run “docker images” you will see the myimage in the list. You can test it by running :
docker run -it -p 3000:8081 myimage
and then in your browser type: localhost:3000 port 3000 is mapped a local port to the port 8081 inside a docker container.
And finally, if you want to push your image to docker hub you can easily run:
docker push myimage