Monday, 21 September 2020

Docker Basics


Docker provides the ability to package and run an application in a loosely isolated environment called a container. With docker containerization, the running of application becomes independent on the type of host/os on which the application is deployed.

Image vs. Container:

Docker images are binary files that contain everything needed to run a specific service. When you instantiate a service from a Docker image, you say that you create a Docker container.

Basic Commands: 

These are the docker commands that you are likely to use frequently:

• docker pull [image]: Pulls the image from the remote registry to your local filesystem

• docker run [image]: Creates a container from the specific image

• docker ps: Lists the active containers

• docker ps -a: Lists all the containers regardless of their states

• docker images: Lists the images on your machine

• docker rm [container]: Removes a running container

• docker rmi [image]: Removes an image from your machine

• docker exec [container]: Executes a command inside the container

• docker build: Creates an image by following the instructions provided in a special file called a Dockerfile


docker build for building image:

docker build -t <DockerFile> .

docker run command in details:

-d option - To run containers in the background, you need to provide the -d parameter in the docker run statement.

-p option - to map container port to host port. The -p parameter expects syntax: host_port:container_port 

--name option - To assign a name to a container, just add the --name your_container_name parameter to the docker run statement

-e option - to provide environment variables as key-value pair, like -e MYSQL_ROOT_PASSWORD=root 

-v option - If you need to keep the container state across container restarts, you need to mount a volume to your containers by adding the -v parameter to the docker run statement.


docker exec - executing commands inside docker:

docker exec -it <container name> /bin/bash to get a bash shell in the container.

docker exec -it <container name> <command> to execute whatever command you specify in the container.


Sharing a docker image in docker hub:

docker tag <dockerImage> <userName>/<dockerImageName>

docker push <userName>/<dockerImageName>


Saving a docker image and loading it in another system

docker save -o <target tar fileName with path> <dockerImageName>

docker load -i <path to image tar file>