Docker helpful commands
What is Docker?
Docker allows you to package an application with its environment and all of its dependencies into a “box”, called a container. Usually, a container consists of an application running in a stripped-to-basics version of a Linux operating system. An image is a blueprint for a container, a container is a running instance of an image.
Helpful commands
Example Dockerfile
:-
FROM node:16
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
RUN npm install
# If you are building your code for production
# RUN npm ci --only=production
# Bundle app source
COPY . .
EXPOSE 8080
CMD [ "node", "server.js" ]
Create a .dockerignore
file in the same directory as your Dockerfile
with following content:
node_modules
npm-debug.log
This will prevent your local modules and debug logs from being copied onto your Docker image and possibly overwriting modules installed within your image.
Building your image
Now we will be building our image, -t
flag allows you to tag your image, to be accessed later
docker build . -t <your app name>
View your image
The command below displays all the docker images being built till now:-
docker images
Run the image
We will be running our image now using the run command with -p
flag which redirects a public port to private port inside the container and -d
flag that runs the container in detached mode.
docker run -p 49160:8080 -d <your app name>
View running containers
docker ps -a
Log output of a running container
docker logs <container id>
SSH inside the container
docker exec -it <container id> /bin/bash
Build Docker image forcefully
docker build --no-cache -t <you app name>
Stop a Docker container
docker stop <container id>
Remove a Docker container
docker rm <container id>