[A] Basic Docker Commands
1. Build an image
docker build -t <tag-image> .2. List an images
docker images3. Run a container
Port exposed by docker (Internal Container) ↓docker run -p 3000:3000 <taged-image-name> ↑ Port exposed by windows (External OS)4.1 List container (currently running)
docker ps4.2 List container (all running and not running)
docker ps -a5. Kill (currently running) Container
docker kill <container-id>6.1 Remove specific container
docker rm <container-id>6.2 Remove all stopped container
docker container prune7. Working with mongo
docker run mongo //this will install dependenciesdocker run -p 27017:27017 mongoCtrl+C to exit from container
[B] Volume
1. Create a volume
docker volume create <volume-database>2. List volume
docker volume ls3. Remove volume
docker volume rm <volume-database>4. Assigning volume to database (mongo)
docker run -v <volume-database>:/data/db -p 27017:27017 mongo/data/db => this is the default place where mongo stores its data in Linux OS
5. Run bash inside a container
docker exec -it <container-id> /bin/bash[C] Network
1. Create a network
docker network create <my-custom-network>2. List networks
docker network ls3. Use network
docker run -p 3000:3000 --name <name(backend)> --network <my-custom-network> <image-tag>
docker run -v <volume-database>:/data/db --name <name(mongodb)> --network <my-custom-network> -p 27017:27017 mongoInitial Dockerfile
FROM mhart/alpine-node:16.4.2
WORKDIR /usr/src/app
COPY package* .
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]Multi stage Dockerfile
FROM mhart/alpine-node:16.4.2 AS base
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
EXPOSE 3000
FROM base AS development
COPY . .
CMD ["npm", "run", "dev"]
FROM base as production
COPY . .
RUN npm prune --production
CMD ["npm", "run", "start"]Building the development image
docker build --target <development> -t <myapp:dev> .
docker run -e MONGO_URI=mongodb://localhost:27017/mydatabase -p 27017:27017 -v .:/usr/src/app <myapp:dev>
-v .:/usr/src/app=> very important line during development -> it map the current Windows directory (.) to container’s Linux directory (/usr/src/app), for hot reloading
Building the production image
docker build --target <production> -t <myapp:prod> .
docker run -e MONGO_URL=mongodb://localhost:27017/mydatabase -p 27017:27017 <myapp:prod>[BULK CODE]
#running db containerdocker run -p 27017:27017 --volume volume1:/data/db --name mongodb --network network1 mongo
#creating the imagedocker build --target development -t app:dev4 .
#running the containerdocker run -v .:/usr/src/app --network network1 -p 3000:3000 app:dev3 //ruNote: use -L flag to trigger nodemon to hot-reload files. i.e.;
nodemon -L index.js
We can run the container in detached mode by using
-dflag. i.e.;docker run -d <image-tag>. it does not hold the terminal for logging.but, then we have to use
docker log <container-id>to see the log of a particular container.