0% found this document useful (0 votes)
82 views10 pages

Essential Docker Commands Overview

This document provides summaries of various Docker container and image commands: - Docker run launches containers from images and docker ps lists running containers. Additional commands like docker stop, start, kill manage container lifecycles. - Docker volumes can be used to persist data outside containers. Commands like docker volume create/ls manage volumes. - Images are built from Dockerfiles using docker build and layers can be inspected with docker history. Images are distributed using docker login/push/pull. - Docker Compose allows defining and running multi-container applications with a single command like docker-compose up. - Docker Swarm turns a pool of Docker hosts into a single, virtual Docker engine. Services are

Uploaded by

Rk Pk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views10 pages

Essential Docker Commands Overview

This document provides summaries of various Docker container and image commands: - Docker run launches containers from images and docker ps lists running containers. Additional commands like docker stop, start, kill manage container lifecycles. - Docker volumes can be used to persist data outside containers. Commands like docker volume create/ls manage volumes. - Images are built from Dockerfiles using docker build and layers can be inspected with docker history. Images are distributed using docker login/push/pull. - Docker Compose allows defining and running multi-container applications with a single command like docker-compose up. - Docker Swarm turns a pool of Docker hosts into a single, virtual Docker engine. Services are

Uploaded by

Rk Pk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Container Commands:

docker run -itd ubuntu /bin/bash -- enter into a container


docker run -itd --name testubuntu ubuntu /bin/bash -- to change the name of
container
docker ps
docker stop contid
docker start/restart
docker kill contid
docker ps -a

docker run -d tomcat


docker run -d -P tomcat
docker run -d -p 1234:8080 tomcat

docker ps

docker run -it -P jenkins /bin/bash


cat /etc/os-release
/usr/local/bin$ ./[Link] -- to start jenkins inside cont

docker ps -aq -- list of all contids (includes died)


docker cp ravi e9903e9b3122:/tmp (source local, dest cont)
docker cp e9903e9b312:/tmp/ravi . (source cont, dest local)
docker exec -it e9903e9b3122 ls /tmp -- list the file copied

docker export e9903e9b3122 >[Link] -- Export a container’s filesystem as a


tar archive
docker import [Link] newimage:v1 -- Import the contents from a tarball to
create a filesystem image , docker images to check

docker logs [OPTIONS] CONTAINER : --follow, --tail ---- show jenkins example

docker ps -a ; docker container prune -- remove unused contaienrs

docker inspect e9903e9b3122 ---- id, created date, image, platform, hsot, ip

-------------------------------------------------

IMAGES:

docker inspect 307457479447 -- about Image


docker history 307457479447 -- for image layers
docker history tomcat

docker commit -m "ubuntu with curl" contid name:tag

docker login

Username: ravindramca43
Password:
WARNING! Your password will be stored unencrypted in /root/.docker/[Link].
Configure a credential helper to remove this warning. See
[Link]
Login Succeeded

docker tag fd14f028beec ravindramca43/image:v1


docker push ravindramca43/image

docker build -t ubuntu:dockfile .

Dockerfile1:

FROM ubuntu
MAINTAINER "Ravi"
RUN apt-get update
RUN apt-get install -y curl vim

Dockerfile2: docker run -d -P imageid

FROM debian:latest
RUN apt-get update
RUN apt-get install -y procps vim curl nginx
EXPOSE 80
CMD /usr/sbin/nginx -g "daemon off;"

Dockerfile3: docker run -d -P imageid

FROM centos
MAINTAINER "Ravi"
RUN yum update -y
RUN yum install -y httpd
EXPOSE 80
CMD ["/usr/sbin/httpd", "-D", "FOREGROUND"]

Dockerfile4:

FROM ubuntu
RUN apt-get -y update && apt-get -y upgrade
RUN apt-get -y install openjdk-8-jdk wget
RUN mkdir /usr/local/tomcat
RUN wget [Link]
[Link] -O /tmp/[Link]
RUN cd /tmp && tar xvfz [Link]
RUN cp -Rv /tmp/apache-tomcat-8.5.35/* /usr/local/tomcat/
EXPOSE 8080
CMD /usr/local/tomcat/bin/[Link] run

options:

FROM
ADD
COPY
ENV
EXPOSE
FROM
LABEL
VOLUME
WORKDIR

The FROM instruction initializes a new build stage and sets the Base Image for
subsequent instructions. As such, a valid Dockerfile must start with a FROM
instruction.

The RUN instruction will execute any commands in a new layer on top of the current
image and commit the results

The main purpose of a CMD is to provide defaults for an executing container.


CMD ["executable","param1","param2"] (exec form, this is the preferred form)
CMD ["param1","param2"] (as default parameters to ENTRYPOINT)
CMD command param1 param2 (shell form)
There can only be one CMD instruction in a Dockerfile. If you list more than one
CMD then only the last CMD will take effect.

The EXPOSE instruction informs Docker that the container listens on the specified
network ports at runtime.

To actually publish the port when running the container, use the -p flag on docker
run to publish and map one or more ports, or the -P flag to publish all exposed
ports and map them to high-order ports.

The ENV instruction sets the environment variable <key> to the value <value>. ENV
myName="John Doe"

The ADD instruction copies new files, directories or remote file URLs from <src>
and adds them to the filesystem of the image at the path <dest>
ADD test /absoluteDir

The COPY instruction copies new files or directories from <src> and adds them to
the filesystem of the container at the path

An ENTRYPOINT allows you to configure a container that will run as an executable.


ENTRYPOINT ["executable", "param1", "param2"] (exec form, preferred)
ENTRYPOINT command param1 param2

The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT,
COPY and ADD instructions that follow it in the Dockerfile
WORKDIR /path/to/workdir

docker save -o [Link] imageid -- to save image to local and scp to remote

docker rmi -- remove all images

docker load < [Link]

-----------------------------------------------------

VOLUMES:
docker volume create my-vol -- to create a new vol
docker volume ls

A volume named my-vol will be created under /var/lib/docker/volumes


cd /var/lib/docker/volumes

see your vol name _data

create something there

run any contaienrs

docker run -d -P -v my-vol:/tmp imagename

docker run -d -P -v /tmp/test:/usr/share/nginx/html nginx --- we can also


directly do like this

In above command
/tmp/test is source path on your host os
/usr/share/nginx/html is dest path

If /tmp/test directory does not exist on your host os it will create it


docker volume create command always creates the volume under
/var/lib/docker/volumes/<vol-name> directory
For custom source directory paths we can follow the above simply.

docker inspect my-vol

docker volume rm my-vol

$ docker volume prune --To remove all unused volumes and free up space

-----------------------------------------------------------------------------------
--------------------

COMPOSE:

Download : look [Link]

curl -L [Link]
compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose

case1: deploy multiple containers from a single image

Compose 1 : docker-compose -f [Link] up --scale web=4 -d ; docker-


compose down

version: '3'
services:
web:
image: nginx
ports:
- "80"
volumes:
- /home/docker/ravi:/usr/share/nginx/html

case 2: deploy multiple containers from multiple images

Compose 2 : docker-compose -f [Link] -p webapps up -d --scale web=2 --


scale app=2

version: '3'
services:
web:
image: nginx
ports:
- "80"
volumes:
- /home/docker/ravi:/usr/share/nginx/html
app:
image: tomcat
ports:
- "8080"

case 3: build multiple images & deploy multiple containers from multiple images
; create compose files in two folders

docker-compose -f [Link] up --scale web=2 --scale app=2 -d

image1 Dockerfile

FROM ubuntu
RUN apt-get -y update && apt-get -y upgrade
RUN apt-get -y install nginx
EXPOSE 80
CMD /usr/sbin/nginx -g 'daemon off;'

image2 Dockerfile

FROM ubuntu
RUN apt-get -y update && apt-get -y upgrade
RUN apt-get -y install openjdk-8-jdk wget
RUN mkdir /usr/local/tomcat
RUN wget [Link]
[Link] -O /tmp/[Link]
RUN cd /tmp && tar xvfz [Link]
RUN cp -Rv /tmp/apache-tomcat-8.5.35/* /usr/local/tomcat/
EXPOSE 8080
CMD /usr/local/tomcat/bin/[Link] run

[Link]

version: '3'
services:
web:
build:
context: .
ports:
- "80"
volumes:
- /home/docker/ravi:/usr/share/nginx/html
app:
build:
context: ./tomcat
ports:
- "8080"

-------------------------------------------------------------------

Docker Swarm

docker swarm init --advertise-addr [Link]

docker swarm join-token manager -- to join as another manager


docker swarm leave

--------------------------------------------------------------------------

Docker Service

docker service create --name web --replicas 4 -p 8080:80 nginx


docker service ps ServiceID

docker service update web --replicas 8

docker node update --availability drain node2


docker node update --availability active node4

--availability Availability of the node (“active”|”pause”|”drain”)

--label-add Add or update a node label (key=value)

--label-rm Remove a node label if exists

--role Role of the node (“worker”|”manager”)

docker node demote Demote one or more nodes from manager in the swarm
docker node inspect Display detailed information on one or more nodes
docker node ls List nodes in the swarm
docker node promote Promote one or more nodes to manager in the swarm
docker node ps List tasks running on one or more nodes, defaults to current node
docker node rm Remove one or more nodes from the swarm

docker node ps node2 node3 node4 -- to see all docker containers

docker service rm servicename

docker node update --label-add node-type=appserver worker1


docker node update --label-add node-type=webserver worker2
docker service create --replicas 2 --constraint '[Link]-type == webserver'
-p 8090:80 --name service nginx

-----------------------------------------------------------------------------------
----------

docker stack :
============

[Link] : docker stack deploy -c [Link] appstack

version: "3"
services:
app:
# replace username/repo:tag with your name and image details
image: nareshmnvs/myapp:latest
deploy:
replicas: 5
restart_policy:
condition: on-failure
resources:
limits:
cpus: "0.5"
memory: 150M
ports:
- "3000:3000"
web:
# replace username/repo:tag with your name and image details
image: nareshmnvs/nginx:v1
deploy:
replicas: 2
restart_policy:
condition: on-failure
resources:
limits:
cpus: "0.1"
memory: 50M
ports:
- "8090:80"
networks:
mynet:

-----------------------------------------------------------------------------------
-
Cobtinuous Deploy

vi /etc/sudoers
jenkins ALL=(ALL) NOPASSWD: ALL

root@ubuntu:/etc/sudoers.d# vi jenkins
jenkins ALL=(ALL) NOPASSWD: ALL

In Jenkins Build Section:


------------------------

rm /tmp/deploy
mkdir /tmp/deploy
cd /tmp/deploy
cp /var/lib/jenkins/workspace/package/target/[Link] .
touch Dockerfile
cat <<EOT>>Dockerfile
FROM tomcat
ADD [Link] /usr/local/tomcat/webapps
CMD "[Link]" "run"
EXPOSE 8080
EOT
sudo docker build -t edureka/deployimage:$BUILD_NUMBER .
sudo docker run -itd --name=deployapp-$BUILD_NUMBER -P edureka/deployimage:
$BUILD_NUMBER

Access app : [Link]

--------------------------------------------

sudo chown jenkins:jenkins /tmp/deploy1


cd /tmp/deploy1
sudo cp /var/lib/jenkins/workspace/package1/[Link] .
sudo touch Dockerfile
sudo chown jenkins:jenkins Dockerfile
sudo cat <<EOT>> Dockerfile
FROM tomcat
ADD [Link] /usr/local/tomcat/webapps
CMD "[Link]" "run"
EXPOSE 8080
EOT
sudo docker build -t ravi/deployimage:$BUILD_NUMBER .
sudo docker run -itd --name=deployapp-$BUILD_NUMBER -P ravi/deployimage:
$BUILD_NUMBER
sudo docker ps

-------------------------------------

Networks:

docker run -d ubuntu sleep 1000 (run two times and see diff ips)
docker inspect 7f0dfc

"Gateway": "[Link]",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "[Link]",

"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "58d04eb694fac3ea778a9a1a03ec015902d47243745a2b
a5b192c6ce52d25463",
----------

docker run -d --net host --name cont1 alpine ping [Link]

see inspect as host

docker run -d --net none --name cont2 alpine ping [Link]

----------

docker network create ravinet


docker network ls

docker run -d --net ravinet --name cont3 alpine ping [Link]

docker swarm init


docker network ls

root@ubuntu:/tmp/deploy# docker network ls


NETWORK ID NAME DRIVER SCOPE
58d04eb694fa bridge bridge local
247120965c44 docker_gwbridge bridge local
2d3b30748098 host host local
nt2kw4mrttvd ingress overlay swarm -- for swarm
4932c2fda7ee none null local
0d1cadac5822 ravinet bridge local

Common questions

Powered by AI

The 'CMD' instruction in a Dockerfile provides defaults for an executing container. It's primarily used to specify the command that runs when the container starts. There can only be one CMD instruction in a Dockerfile, and if multiple are specified, only the last one will take effect. It can also pass default parameters to an ENTRYPOINT instruction if it exists, allowing for executable configuration. This interaction emphasizes the role of CMD as setting default commands to be run in the absence of explicit instructions when launching a container or supplementing the ENTRYPOINT command execution .

Storing Docker credentials unencrypted, as seen in Docker's default behavior when using 'docker login,' poses a significant security risk as it exposes credentials to unauthorized access if the filesystem is compromised. To mitigate this, it's recommended to utilize Docker's credential helper, which integrates with the native OS credential store to encrypt and manage Docker credentials securely. Alternative measures include using environment variables for passing credentials and setting up two-factor authentication for Docker Hub accounts. Implementing these measures significantly enhances security by safeguarding against credential theft and unauthorized image repository access .

The 'docker volume' command enhances container data management by creating, listing, inspecting, and removing volumes that provide persistent data storage independent of the container lifecycle. Volumes facilitate data sharing between containers and help maintain data persistence after containers are stopped or removed, which is crucial for stateful applications. By default, a volume is stored on the host filesystem under '/var/lib/docker/volumes', allowing easy access and management. This functionality is particularly advantageous for scenarios where data retention and inter-container data sharing are critical .

While both 'ADD' and 'COPY' are used to transfer files to an image, they differ in functionality and use cases. 'COPY' is simpler and only supports local source files or directories for direct copying into the container's filesystem at a specified path. 'ADD,' in addition to copying local files, can also handle URLs for downloading and automatically extract compressed files inside the image. Choosing 'ADD' over 'COPY' is beneficial when fetching files from remote URLs or dealing with tarball extraction, while 'COPY' is more efficient and clear for moving local files and directories .

Continuous Deployment using Docker and Jenkins significantly automates the software release process by integrating build compilation, containerization, and deployment into an end-to-end pipeline. Jenkins orchestrates the build tasks, running specified scripts to package applications into Docker images. These images are then launched and tested automatically. This approach drastically reduces manual intervention, minimizes deployment errors, and accelerates time to market by ensuring each code change can be quickly and consistently delivered to production. It enhances scalability, repeatability, and reliability of software releases in agile development environments .

Docker Networking allows containers to communicate with each other and the external world by providing a network abstraction layer. It supports several network drivers including 'bridge,' 'host,' 'overlay,' and 'macvlan.' The 'bridge' driver is the default for container networks on a single host; 'host' allows containers to use the host's networking stack; 'overlay' enables communication between containers across different Docker hosts, especially in swarm mode; and 'macvlan' offers direct access to physical network interfaces, useful for legacy applications. These drivers are pivotal in managing how containers are isolated and communicate within the Docker ecosystem and with external systems .

Docker Compose scales services by using the 'scale' option in the command or specified in the Compose file, allowing multiple container instances of a service to run. This is particularly useful for load balancing and redundancy. The 'docker-compose up --scale service_name=number' command specifies the number of containers for a given service. For deploying multiple instances, the 'docker-compose.yml' file can configure service names, images, ports, and volumes. This configuration ensures that each service runs the desired number of replica containers, offering fault tolerance and enhanced load distribution .

Docker Swarm serves as a native clustering and scheduling tool for Docker containers, providing features for high availability and scalability in managing large sets of containerized applications. It adds value to standalone Docker installations by abstracting container orchestration tasks, allowing easy deployment, management, and scaling across a swarm of Docker hosts. Unlike standalone Docker, Docker Swarm supports service discovery, load balancing, and rolling updates, making it suitable for production environments requiring robust distributed application architecture. It contrasts with standalone setups by offering a built-in transport layer security and automatic failover, significantly enhancing operational efficiency and resilience .

The 'EXPOSE' instruction in a Dockerfile indicates to Docker which ports the container's application listens on at runtime, making it visible to linked containers. However, it doesn’t map the container's ports to the host system. For this, the '-p' flag is used in the 'docker run' command to publish the container's ports on the host system, allowing external traffic to access these ports. This two-step pairing ensures separation of concerns: 'EXPOSE' informs about available ports while '-p' facilitates actual port mapping and exposure to outside networks .

Docker's 'commit' command allows saving the current state of a container as a new image, enabling version control by capturing changes made within the container. This capability is essential for iteratively developing applications, maintaining specific container states, and facilitating rollback to previous versions when needed. The 'push' command complements this by uploading committed images to a remote registry like Docker Hub, allowing for sharing, collaboration, and deployment across different environments. Combined, these commands streamline image lifecycle management and versioning in DevOps practices .

You might also like