Essential Docker Commands Overview
Essential Docker Commands Overview
docker ps
docker logs [OPTIONS] CONTAINER : --follow, --tail ---- show jenkins example
docker inspect e9903e9b3122 ---- id, created date, image, platform, hsot, ip
-------------------------------------------------
IMAGES:
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
Dockerfile1:
FROM ubuntu
MAINTAINER "Ravi"
RUN apt-get update
RUN apt-get install -y curl vim
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;"
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 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
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
-----------------------------------------------------
VOLUMES:
docker volume create my-vol -- to create a new vol
docker volume ls
In above command
/tmp/test is source path on your host os
/usr/share/nginx/html is dest path
$ docker volume prune --To remove all unused volumes and free up space
-----------------------------------------------------------------------------------
--------------------
COMPOSE:
curl -L [Link]
compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
version: '3'
services:
web:
image: nginx
ports:
- "80"
volumes:
- /home/docker/ravi:/usr/share/nginx/html
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
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 Service
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 stack :
============
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
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
--------------------------------------------
-------------------------------------
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",
----------
----------
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 .