Docker Commands Everyone Should Know: [Short Note]
Tags: docker, devops, webdev, beginners
Published: 2021-11-17 20:03:19

## About This Article

This article is a short note of some of the essential Docker commands that I think are useful for beginners.

**Tip:** I have created this short note while following the tutorial. I invite you to follow this [Docker Tutorial for Beginners [FULL COURSE in 3 Hours]](https://youtu.be/3c-iBn73dDE) and subscribe to her channel. She is doing a stunning job.

&nbsp;

## Docker Commands


### Pulling a docker container image

```console
# syntax
docker pull <docker-image>

# example
docker pull postgres
```
&nbsp;

### Pulling a specific version of a docker container image

```console
# syntax
docker pull <docker-image>:<specify-the-version-here>

# example
docker pull postgres:9.6
```

&nbsp;

### Pulls the docker image and runs/starts the docker container | starts new container with a command

```console
# pulls and starts the latest docker image
docker run postgres  

# or you can specify the version
docker run postgres:9.6
```

&nbsp;

### To see all the running containers | lists all the running containers

```console 
docker ps
```

### Check all the **existing images** in the machine

```console 
docker images
```

&nbsp;

### Create a **new** container of an image

**Tip:** Please note that `run` command deals with Docker Images.

```console
# syntax
docker run <docker-image>

# example
docker run redis
```

&nbsp;

### Run a container in detached mode

**Tip:**  We can get the hashed ID of the container with this command.
`--detach` or `-d` means detached mode (Run container in background and print container ID)


```console
docker run -d redis
```

&nbsp;

### Start and stop docker container | a.k.a restart a container (existing container)


**Tip:** `start` and `stop` command deals with existing docker containers. 


```console
# For example, you can restart a stopped container.
# syntax
docker start <hashed-ID-of-the-docker-container>
```  

```console
# For example you can stop a running container.
# syntax
docker stop <hashed-ID-of-the-docker-container>
```

&nbsp;

### Lists running and stopped containers | a.k.a history of running and stopped containers

```console
docker ps -a
```

&nbsp;

### Binding ports between the host and the container


`6000` 
: port specified for the host.  
`6379`
: port of the container.  

```console
# since we did not specify a version of redis, it will bind to the latest one available. 
docker run -p6000:6379 redis
```

```console
# starts with the detached mode.
docker run -p6000:6379 -d redis
```

&nbsp;

#### Binding ports between the host and a different version of a container

```console
# here I have to specify a different port for the host because port 6000 is already bound to to the container (redis latest version)
docker run -p6001:6379 -d redis:4.0
```

&nbsp;

### Debugging containers

#### To see the logs redis container is producing

```console
# hashed ID of the running container of redis (we can get the hashed ID using `docker ps`)
docker logs <hash ID>`

# or name of the container (we can get the name using `docker ps`)
docker logs <name of the container>
```

&nbsp;

#### Change the name of the container

**Tip:** `old-redis-container` is the name I have given for the container. 

```console
docker run -d -p6001:6379 --name old-redis-container redis:4.0
```
and,

**Tip:** `latest-redis-container` is the name I have given for the container.
```console
docker run -d -p6000:6379 --name latest-redis-container redis
```

&nbsp;

#### To see the container's stuffs

```console 
docker exec -it <container hashed ID or container-name> /bin/bash

# or (sometimes `/bin/bash` will not work)
docker exec -it <container hashed ID or container-name> /bin/sh
``` 

- `-it` means 'Interacting Terminal'. We can use this terminal to interact with the container and see what is going on with the root access.
- We can use some basic commands too, for example: `ls`, `pwd`, `env`
- To exist from the container we can type `exist` command.  

&nbsp;

## Docker Network Commands

### List out all the docker networks

```console 
docker network ls
```

&nbsp;

### Create a Docker Network

```console 
docker network create <name-of-the-network>

#example
docker network create mongo-network
```

&nbsp;

### Let's connect mongo and mongo-express

1. Let's deal with MongoDB. Following command will start the mongo container.

```text
docker run -d \                                 ---> We are going to start the container in detached mode.
-p:27017:27017 \                                ---> Binding ports for host and container (specifying ports).
-e MONGO_INITDB_ROOT_USERNAME=mongoadmin \      ---> Environment variable for username.
-e MONGO_INITDB_ROOT_PASSWORD=secret \          ---> Environment variable for password.
--name my_mongodb_container \                   ---> Gives a name to mongo container, ex: `my_mongodb_container`.
--network mongo-network \                       ---> Specifying the docker network. `mongo-network`
mongo

```

- `docker logs <hashed ID of the container>` ---> We can check the logs to see if the Mongo container works properly.


1. Let's deal with Mongo-express. Following command will start the mongo-express container.

```text

docker run -d \                                         ---> We are going to start the container in detached mode.
 -p 8081:8081 \                                         ---> Binding ports for host and container (specifying ports).
-e ME_CONFIG_MONGODB_ADMINUSERNAME=mongoadmin \         ---> username
-e ME_CONFIG_MONGODB_ADMINPASSWORD=secret \             ---> password
-e ME_CONFIG_MONGODB_SERVER=my_mongodb_container \      ---> Name of the Mongo container.
--name my_mongo_express_container \                     ---> Gives a name to mongo container, ex: `my_mongo_express_container`.
--network mongo-network \                               ---> Specifying the docker network. ex: `mongo-network`.
mongo-express

```

- `docker logs <hashed ID of the container>` ---> We can check the logs to see if the Mongo-express container works properly.
- We can also open up the web browser, and check mongo-express by opening `http://localhost:8081`

&nbsp;

## More with logs

### Display the last part of the log.

```console 
docker logs <hashID-of-the-container> | tail
```

&nbsp;

### We can get the logs, then we can make a "-----------" line, then we can see the new logs clearly below that line.

```console
docker logs -f
```

&nbsp;

### Docker Compose

- It is exhausting to run commands when you want to run multiple containers.
- Docker Compose is a tool for defining and running multi-container Docker applications.  

&nbsp;

### Docker compose file. 

```yml
# docker-compose.yml file
version: "3"
services:
    my_mongodb_container:
        image: "mongo"
        ports:
            - "27017:27017"
        environment:
            - MONGO_INITDB_ROOT_USERNAME=admin
            - MONGO_INITDB_ROOT_PASSWORD=password

    my_mongo_express_container:
        image: "mongo-express"
        ports: 
            - "8081:8081"
        environment:
            - ME_CONFIG_MONGODB_ADMINUSERNAME=admin
            - ME_CONFIG_MONGODB_ADMINPASSWORD=password
            - ME_CONFIG_MONGODB_SERVER=my_mongodb_container


```

- Here docker compose takes care of creating a common network. 
- We do not have to worry about specifying and creating a network like we did in the command (like this `--network`)

&nbsp;

### How to run the docker compose file.

- Assume that `docker-compose.yml` file is in the project directory.  
- Let's open up the terminal (from your project directory) and type following command.  
  
  ```console 
  docker-compose -f docker-compose.yml up
  ```
&nbsp;

### How to stop the docker containers using docker-compose file. 

- To stop the docker containers type following command.
- Please note that following command will also remove the docker network which created when we run the `docker-compose.yml`

    ```console 
    docker-compose -f docker-compose.yml down
    ```

&nbsp;

### Docker file

- It is a blueprint for building docker images.
- All the commands that are in the dockerfile will apply to the docker container environment.  

```Dockerfile
# save the file as a simple text file. File name should be `Dockerfile`
FROM node

ENV MONGO_DB_USERNAME=admin \
    MONGO_DB_PWD=password

RUN mkdir -p /home/app

COPY ./home/app

CMD ["node", "/home/app/server.js"]

```

&nbsp;

### How to build the Docker Image using Dockerfile

- To create the Docker Image, type following command.

```console
# syntax
docker build -t <name-of-the-image:tag> <location-of-the-Dockerfile>

# example
docker build -t my-app:1.0 .
```

&nbsp;

### Let's run Docker Image that we have created with

```console
docker run my-app:1.0
```

&nbsp;

### How to delete a Docker Image

1. Delete the `my-app` Docker Container.
2. Delete the `my-app` Docker Image.

```console
# let's list the Docker Images in the machine.
docker images

# let's list all the docker containers (history).
docker ps -a

# let's find out what Docker Container do we have to delete in order to delete the `my-app` Docker Image.
docker ps -a | grep my-app:1.0

# let's delete the Docker Container before we delete `my-app` Docker Image
docker rmi <hashedID-of-the-docker-container>

# then, we can remove the Docker Image using the hashID
docker rmi <hashID-of-the-image>

# Now, when we list down all the images, we do not see the Docker Image.
docker images

# [Optional Step] Then, if we want to rebuild the Docker Image
docker build -t my-app:1.0 .

# [Optional Step] After building successful, we can run our docker image
docker run my-app
```