Services >> Containers >> Docker >> Examples on how to use docker command line

your_gcp_project_id


## To get started, if you want to run docker as non-root user
## Make the current user a member of docker group. 
## Set docker as the secondary group for that user and then logout and re-login

sudo usermod -aG docker ${USER}


## get help on docker command or subcommands

docker --help

docker run --help

...


## Run a container image
## if the image does not exist locally, it will be downloaded from the dockerhub repository and then run

docker run hello-world

(command output)
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pull complete
Digest: sha256:9ade9cc2e26189a19c2e8854b9c8f1e14829b51c55a630ee675a5a9540ef6ccf
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/


## List container images saved locally

docker images

(Command output)
REPOSITORY     TAG      IMAGE ID       CREATED       SIZE
hello-world    latest   1815c82652c0   6 days ago    1.84 kB


## List running containers

docker ps

(command output)
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES


## List all containers, including those that finished executing

docker ps -a

(command output)
CONTAINER ID   IMAGE         COMMAND    CREATED              STATUS                          PORTS     NAMES
2a7203d68bb9   hello-world   "/hello"   About a minute ago   Exited (0) About a minute ago             wizardly_buck



## For the following command to build a docker image, use the following files
## in your current directory

Filename Contents
Dockerfile # Use an official Node runtime as the parent image
FROM node:6
# Set the working directory in the container to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
ADD . /app
# Make the container's port 80 available to the outside world
EXPOSE 80
# Run app.js using node when the container launches
CMD ["node", "app.js"]
app.js const http = require('http');
const hostname = '0.0.0.0';
const port = 80;
const server = http.createServer((req, res) => {
    res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
        res.end('Hello World\n');
});
server.listen(port, hostname, () => {
    console.log('Server running at http://%s:%s/', hostname, port);
});
process.on('SIGINT', function() {
    console.log('Caught interrupt signal and will exit');
    process.exit();
});


## Build the container image, note there is a . (period) at the end
## to indicate using current working directory

docker build -t node-app:0.1 .

(command output)
Sending build context to Docker daemon  3.072kB
Step 1/5 : FROM node:6
6: Pulling from library/node
c5e155d5a1d1: Pull complete
221d80d00ae9: Pull complete
4250b3117dca: Pull complete
3b7ca19181b2: Pull complete
425d7b2a5bcc: Pull complete
69df12c70287: Pull complete
ea2f5386a42d: Pull complete
d421d2b3c5eb: Pull complete
Digest: sha256:e133e66ec3bfc98da0440e552f452e5cdf6413319d27a2db3b01ac4b319759b3
Status: Downloaded newer image for node:6
 ---> ab290b853066
Step 2/5 : WORKDIR /app
 ---> Running in a9bfa21571ea
Removing intermediate container a9bfa21571ea
 ---> 685ad590ba8d
Step 3/5 : ADD . /app
 ---> c0694365e45b
Step 4/5 : EXPOSE 80
 ---> Running in 68bea46d597e
Removing intermediate container 68bea46d597e
 ---> 22d4e3b4bc92
Step 5/5 : CMD ["node", "app.js"]
 ---> Running in 2955c33907f9
Removing intermediate container 2955c33907f9
 ---> 5578be340c58
Successfully built 5578be340c58
Successfully tagged node-app:0.1


## Run the container image just built above
## mapping the container's port 80 to port 4000 of the host that you are on now

docker run -p 4000:80 --name my-app node-app:0.1

(command output)
Server running at http://0.0.0.0:80/


## test accessing the app on your local machine (from another terminal or SSH session) by

curl http://localhost:4000

(command output)
Hello World


## To stop the above app (from another terminal)
## list the running container and confirm the NAME or ID

docker ps

(command output)
CONTAINER ID   IMAGE          COMMAND         CREATED         STATUS         PORTS                                   NAMES
78b300012906   node-app:0.1   "node app.js"   3 minutes ago   Up 3 minutes   0.0.0.0:4000->80/tcp, :::4000->80/tcp   my-app

docker stop my-app

(command output)
my-app


## remove the container

docker rm my-app

(command output)
my-app


## we can run the container again as the image is already built and available locally
## we can run in the background by adding -d option

docker run -p 4000:80 --name my-app -d node-app:0.1
docker ps

(command output)
e541a04923dbce904430e8187c48ddb07ae43fd205cc3cc98b1b2001772f984f

CONTAINER ID   IMAGE          COMMAND         CREATED          STATUS          PORTS                                   NAMES
e541a04923db   node-app:0.1   "node app.js"   25 seconds ago   Up 22 seconds   0.0.0.0:4000->80/tcp, :::4000->80/tcp   my-app



## to view the container log

docker logs e541a04923db

(command output)
Server running at http://0.0.0.0:80/


## to view and follow the log in realtime

docker logs -f e541a04923db

(command output)
Server running at http://0.0.0.0:80/


## after making changes to your application code
## e.g. change the output from "Hello World" to "Good Morning World"
## you can build a new container image with a different tag (-t) e.g. version 0.2

docker build -t node-app:0.2 .

(command output)
Sending build context to Docker daemon  3.072kB
Step 1/5 : FROM node:6
 ---> ab290b853066
Step 2/5 : WORKDIR /app
 ---> Using cache
 ---> 685ad590ba8d
Step 3/5 : ADD . /app
 ---> 928332e6d3fc
Step 4/5 : EXPOSE 80
 ---> Running in b42113a4531e
Removing intermediate container b42113a4531e
 ---> d66f871e3d1e
Step 5/5 : CMD ["node", "app.js"]
 ---> Running in a00a136c3792
Removing intermediate container a00a136c3792
 ---> 0a8987bc5bc7
Successfully built 0a8987bc5bc7
Successfully tagged node-app:0.2


## we can run the new version of the container and map to a different port on the host

docker run -p 8080:80 --name my-app-2 -d node-app:0.2
docker ps


(command output)
16c65e7b2ddb798aaaf9c6226ff0cbf5f780f8fe517005d188e70131e0e21868

CONTAINER ID   IMAGE          COMMAND         CREATED          STATUS          PORTS                                   NAMES
16c65e7b2ddb   node-app:0.2   "node app.js"   4 seconds ago    Up 1 second     0.0.0.0:8080->80/tcp, :::8080->80/tcp   my-app-2
d2c284301b72   node-app:0.1   "node app.js"   12 minutes ago   Up 12 minutes   0.0.0.0:4000->80/tcp, :::4000->80/tcp   my-app



## to run interactive bash session inside the running container

docker exec -it 16c65e7b2ddb bash

(command output)
root@16c65e7b2ddb:/app# pwd
/app
root@16c65e7b2ddb:/app# ls
Dockerfile  app.js
root@16c65e7b2ddb:/app# exit


## To view the container's metadata

docker inspect 16c65e7b2ddb

(command output)
[
    {
        "Id": "16c65e7b2ddb798aaaf9c6226ff0cbf5f780f8fe517005d188e70131e0e21868",
        "Created": "2021-10-12T02:33:31.92387841Z",
        "Path": "node",
        "Args": [
            "app.js"
        ],
        "State": {
            "Status": "running",
            "Running": true,

... TRUNCATED TO SAVE SPACE ...

                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:03",
                    "DriverOpts": null
                }
            }
        }
    }
]


## To examine a specific metadata of the container

docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' 16c65e7b2ddb

(command output)
172.17.0.3


## To push docker image to a reposity like Google Container Registry (gcr.io)
## do it from a machine with docker and Gcloud sdk installed (gcloud command line)
## or from your GCP account's cloud shell
## Have your GCP project_id
## assuming we have the node-app:0.2 image built as above
## create a TAG target image on GCR repository for that docker image

docker tag node-app:0.2 gcr.io/your_gcp_project_id/node-app:0.2
docker images

(command output)
REPOSITORY                             TAG       IMAGE ID       CREATED              SIZE
node-app                               0.2       f93f95d979b9   About a minute ago   884MB
gcr.io/fluent-sprite-326604/node-app   0.2       f93f95d979b9   About a minute ago   884MB
node-app                               0.1       838564ea7a00   6 minutes ago        884MB
node                                   6         ab290b853066   2 years ago          884MB


## To push to GCR, we need to have docker configured with the credentials to authenticate with
## the container registry.  Follow the instructions here, depending on your scenario
## Push our image to the registry

docker push gcr.io/your_gcp_project_id/node-app:0.2

(command output)
The push refers to repository [gcr.io/your_gcp_project_id/node-app]
b7d56ac43d4b: Pushed
739ab0dcd874: Pushed
f39151891503: Pushed
f1965d3c206f: Pushed
a27518e43e49: Pushed
910d7fd9e23e: Pushed
4230ff7f2288: Pushed
2c719774c1e1: Pushed
ec62f19bb3aa: Pushed
f94641f1fe1f: Pushed
0.2: digest: sha256:a1a4bad4ac06c128bf573d82774d6c9fa392a3a2d9c84b35c15a28fb1044bb18 size: 2422



## To use this docker image on another machine with the required credential to the registry
## pull the image from the registry

docker pull gcr.io/your_gcp_project_id/node-app:0.2

(command output)
0.2: Pulling from your_project_id/node-app
Digest: sha256:a1a4bad4ac06c128bf573d82774d6c9fa392a3a2d9c84b35c15a28fb1044bb18
Status: Downloaded newer image for gcr.io/
your_project_id/node-app:0.2



## run and test the app

docker run -p 5000:80 -d gcr.io/your_gcp_project_id/node-app:0.2
curl http://localhost:5000






Official Reference: https://docs.docker.com/engine/reference/commandline/cli/