#cmd vs entrypoint
Explore tagged Tumblr posts
arjunphp-blog · 1 year ago
Text
Docker difference between cmd and entrypoint
In Docker, both CMD and ENTRYPOINT are instructions used in a Dockerfile to define how a container should run an application. However, they serve slightly different purposes CMD: This instruction specifies the default command to be executed when a container starts. It can be overridden by passing arguments to docker run. If a Dockerfile has multiple CMD instructions, only the last one will take…
View On WordPress
0 notes
rexavki · 2 years ago
Video
youtube
Dockerfile : CMD vs ENTRYPOINT mais c'est quoi la différence ??
0 notes
nitishjadia · 6 years ago
Text
Docker Beginner's Guide
Installation
Refer to DigitalOcean's post here or Official docker installation page. https://docs.docker.com/engine/installation/
Basics
Check whether docker is running or not
docker run hello-world
You can try this as well:
docker run -ti debian bash
-ti -> terminal interactive
Check list of images
docker images
Pulling images
docker pull ubuntu:xenial
if tags are not provided then latest is assumed.
Run docker container from images
If image doesn't exist then it'll be pulled from the hub.
docker run -ti ubuntu:latest bash
ubuntu -> image latest -> tag (optional, by default it's latest) bash -> what do we want to do with the image.
Check running images
docker ps
[or]
docker ps --format = $DOCFORMAT
$DOCFORMAT-> variable with value: DOCFORMAT="table {{.ID}}\t{{.Image}}\t{{.Command}}\t{{.Names}}"
docker ps -l --format = $DOCFORMAT
-l -> get info about last exited container
docker ps -a
-a -> get info about all the containers present
Run a process and delete the container after that
docker run --rm -ti ubuntu sleep 5
This runs sleep for 5 sec and then exists. --rm-> removes the container after exit
docker run -ti ubuntu bash -c "sleep 3; echo all done"
This send command to bash.
Removing images and containers
Removing containers
docker ps -a docker rm laughing_hodging fellow_docks
Add -f if container is still running and you want to remove it.
Find number of containers:
docker ps -a -q | wc -l
-q-> lists all the containerIDs
Remove all the containers:
docker rm `docker ps -a -q`
Removing images
docker images docker rmi ubuntu:latest nginx:latest
Note: An image cannot be removed if a container is still using it as a referenced image. So,before removing an image, remove all its associated containers first. You can use -f to force remove the image, leaving behind orphan containers.
Leave container running in background(detatch)
docker run -d -ti ubuntu /bin/bash
-d -> detaches the container
docker -ps --format $DOCFORMAT
output will show the running container
NAME suspicious_williams
Naming containers
docker run -d -ti --name container8 ubuntu:latest /bin/bash
--name-> name a container instead of getting a random name.
Renaming a container:
docker rename laughing_hodging container9
Note: Running containers can also be renamed. Because internally everything is handled using containerIDs.
Attach to a container
docker attach suspecious_williams
Detatch SHORTCUT:
CTRL+P then CTRL+Q
Docker info
System wide information like: number of containers, supported and non supported services, etc
docker info
Restart an exited container:
docker restart zeolous_darwin
zeolous_darwin-> instead of name we can use container ID as well.
Get all information about a container
docker inspect blisful_saha
You can even use grep to zero down on specific information
docker inspect blisful_saha | grep -i ip
Search for an image from CLI
docker search ubuntu
One base image (ubuntu) can be used to make multiple containers and anything that happens inside the container won't affect the other containers or the base image.
Container -> Image
Why? Assume, ubuntu doesn't have vim installed by default. So, me make a container of ubuntu, install vim in that and make image of that container. Use this image to make more containers, now you will have vim already installed in your container.
How to do that?
Make changes in container, commit it.
Using Dockerfile
1. Using commit
create a container and install vim.
docker run -ti ubuntu /bin/bash
now we will be inside the container
apt-get update apt-get install vim -y cd ~ echo "This machine has vim installed." > hello.txt
exit the container. use ps to check last exited container
docker ps -l
output:
ad5ab2e8fe2f ubuntu "/bin/bash" 42 minutes ago Exited (0) 19 seconds ago jovial_herschel
docker restart jovial_herschel docker attach jovial_herschel
you will notice that helloFile and vim are already there.
Let's commit this container now.
docker commit -m "Installed vim, added hello file" -a "nitish" jovial_herschel nitishmod/ubuntuvim:v1
-a-> author -m-> message
output:
sha256:6cf3de1a8084ae70b8b997c4f1df14b822e582133f3c8d94a703be902a74a4ce
look into docker images to verify our image is there or not
docker images
output:
nitishmod/ubuntuvim v1 6cf3de1a8084 About a minute ago 170MB
Let's use this custom image to make new container.
docker run -ti nitishmod/ubuntuvim:v1 /bin/bash
We will be having vim and hello file there.
2. Using Dockerfile
mkdir build cd build vim Dockerfile
Add the following lines in Dockerfile:
#This is a custom ubuntu image with vim already installed FROM ubuntu:xenial MAINTAINER nitish <[email protected]> RUN apt-get update RUN apt-get install -y vim
NOTE: Here, RUN runs the command at build time, so the result will become a part of the image we are creating.
docker build -t="nitishmod/ubuntuvim:v2" .
-t-> title .-> dot, because Dockerfile is in the same folder. We can also feed Dockerfile from a path.
docker build -t="nitishmod/ubuntuvim:v2" < /home/Dockerfile
Check new images with docker images
Exec
you can run commands without logging into the container
docker exec laughing_hodging cat /etc/passwd
and you'll get the output of cat /etc/passwd on this container. If a container is not running then this command won't work.
Stop
Stop the container from running when in background.
docker stop laughing_hodging
Logs
Can also be used to check output of containers.
docker logs laughing_hodging
useful with stopped containers, detatched containers.
Monitoring process inside containers
We can use top to check all the running processes inside the container.
docker top laughing_hodging
but the output is just a snapshot. docker stats - Display a live stream of container(s) resource usage statistics
docker stats distracted_napier
Ports
By exposing ports we can connect one port from base machine to another from port of container.
docker pull nginx:latest docker run -d -p 80:80 nginx:latest
p -> port 80:80 -> inside the container : outside the container
docker run -d -p 8080:80 nginx:latest
Local machine (with 8080) will be directly connected to port 80 of container.
try http://localhost:8080 and you'll reach nginx default webpage.
Mapping all container ports to random host ports:
docker run -d -P nginx:latest
Mapping specific container port to random host port:
docker run -d -p 80 nginx:latest
Binding container port to a specific IP:
docker run -d -p 127.0.0.1:8080:80 nginx:latest elinks http://127.0.0.1:8080
User management in container
Always giving root access in containers is not recommanded so we will make an image with a non-priviliged user.
docker pull centos:latest mkdir runAsUser vim Dockerfile
Add the following lines in Dockerfile:
# Dockerfile based on the latest CentOS 7 image - non-privileged user entry FROM centos:latest MAINTAINER [email protected] # Make a new user RUN useradd -ms /bin/bash user # I'll try to login as user USER user
Build the image and make a container:
docker build -t="custom/centos7:nonroot" . docker images docker run -ti custom/centos7:nonroot /bin/bash
You will notice that you logged in as user and it's not possible to switch to root user from inside the container. So, we will restart the container and use exec to login as root user.
docker ps -l docker start wizardly_haibt docker exec -u 0 -ti wizardly_haibt /bin/bash
-u 0-> will run /bin/bash with userID 0 which is root.
Order of execution of commands matters in Dockerfile. For eg: we try to make a new file /etc/hello.txt during build.
vim Dockerfile
Add following entries:
# Dockerfile based on the latest CentOS 7 image - non-privileged user entry FROM centos:latest MAINTAINER [email protected] # Make a new user RUN useradd -ms /bin/bash user # I'll try to login as user USER user RUN echo "Test" >> /etc/hello.txt
docker build -t=centos7:configv1 .
output:
/bin/sh: /etc/hello.txt: Permission denied
Why did this happen? Because swtiched to user and then tried to create hello.txt, in this case only root has the permission to create file in /etc.
Try this:
# Dockerfile based on the latest CentOS 7 image - non-privileged user entry FROM centos:latest MAINTAINER [email protected] # Make a new user RUN useradd -ms /bin/bash user # Create file as root RUN echo "Test" >> /etc/hello.txt # Login as user USER user
Dockerfile
ENV
set environment variables systemwide.
RUN export JAVA_HOME /etc/java/ will set environment variable only on one user.
ENV DB_HOST = db.production.example. ENV DB_port = 5432
RUN vs CMD
RUN will run during image build process and CMD will run when you start the container of this image.
CMD "echo" "Welcome to new container!"
CMD will only run when you don't provide any parameters while docker run.
docker run --rm -ti centos7:echov1 /bin/bash
won't run our CMD.
ENTRYPOINT
An ENTRYPOINT allows you to configure a container that will run as an executable.
Dockerfile:
# Dockerfile based on the latest CentOS 7 image - non-privileged user entry FROM centos:latest MAINTAINER [email protected] # Make a new user RUN useradd -ms /bin/bash billy ENTRYPOINT echo "Welcome to new container!"
Whenever we will start the container the container will only run this echo command.
This helps when you dedicate a container for only one task.
docker run -i -t --rm -p 80:80 nginx
You can override the ENTRYPOINT instruction using the docker run --entrypoint flag. or we can use exec to run a command inside the running container.
docker exec -it nginx ps aux
EXPOSE
To expose a port of the container for inter-container communication.
# This image is based on CentOs 7 and will start apache service in each container. FROM centos:latest MAINTAINER [email protected] RUN yum update -y RUN yum install -y httpd net-tools vim # Port 80 will be opened EXPOSE 80 RUN echo "This is the site sitting inside a container!" > /var/www/html/index.html ENTRYPOINT apachectl "-DFOREGROUND"
build an image and a container. if you do docker ps then you will see that this container has port 80 exposed.
docker run -d --rm --name webserver -P centos7:apachev2
-P-> will bind host's random port to container's port 80 (in this example).
docker run -d --rm --name webserver -p 8888:80 centos7:apachev2
-p-> bind :
Volume management
Two types of volumes:
Persistent - Data stays after container stop.
Ephemeral - Data is lost after container is killed.; Evaporates when not in use.
Persistent
Sharing data between linux machine and hosts
mkdir example pwd
output: /home/docker
We have created a folder to share.
docker run -ti -v /home/docker/example:/shared-folder ubuntu bash
When you are inside the container:
cd /shared-folder/
Hence, shared-folder is present in container which is linked to the shared folder present on the host. The data inside is shared the folder. Note: Exiting the container won't delete data.
Ephemeral
Sharing data between container
docker run -ti -v /shared-data ubuntu bash
Run the following in container:
echo hello > /shared-data/datafile
output: New file will be created in the shared data.
Network
By default docker's network has 172.17.0.0/24 network.
List all the networks IDs:
docker network ls
information about each host:
docker network inspect bridge docker network inspect host docker network inspect none
man docker-network-create to check man page.
Creating new network adapter
docker network create --subnet 10.1.0.0/24 --gateway 10.1.0.1 mybridge01
Removing a network adapter
BEWARE! Do not remove original 3 network adapters. If you do so, it's better to reinstall docker again!
docker network rm mybridge01
Static IP of a container
docker network create --subnet 10.1.0.0/16 --gateway 10.1.0.1 --ip-range=10.1.4.0/24 --driver=bridge --label=host4network mybridge04
--subnet 10.1.0.0/16-> means bridge is part of this subnet but IP's will be alloted from --ip-range=10.1.4.0 to 10.1.4.255. --driver-> this can be changed depending on the requirement. mybridge04-> our new network name
docker run -it --name nettest1 --net mybridge04 centos:latest /bin/bash
Any available IP from range 10.1.4.0-255 will be provided to this container. For static IP:
docker run --rm -it --name nettest2 --net mybridge04 --ip 10.1.4.100 centos:latest /bin/bash
use docker inspect nettest2 | grep -i ipaddress to verify the IP of the container.
Events
Get real time events from the server
docker events
waits and shows the current events.
docker events --since '1h' docker events --since '2017-01-05T00:35:30' --until '2017-01-05T00:36:05'
--filter output based on conditions provided.
docker events --filter 'event=stop' docker events --filter event=die --filter event=attach
die-> when you exit a container.
Refer: Official Doc
Load and save images
Save images elsewhere.
docker save --output centos.mine.tar centos:mine
use gzip to compress the image:
gzip centos.mine.tar
Loading from the tar.gz or tar:
docker load --input centos.mine.tar.gz
Images history
What were the operations performed to create that image.
docker history nginx:latest
Tag images
Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE.
docker tag 0e5574283393 fedora/httpd:version1.0
or
docker tag httpd fedora/httpd:version1.0
Building you own bridge
Refer here. Stop the docker daemon and add a new bridge.
systemctl stop docker ip link add br10 type bridge ip addr add 10.10.100.1/24 dev br10 ip link set br10 up ip addr sudo ip link set docker0 down dockerd -b br10 &
On a different terminal start using docker. Now, all the container will get IPs from 10.10.100.0 network.
Quick References
Find IP of a container
docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' laughing_hodging
References
Most of the references are from docker docs.
Docker Overview
Run
Dockerfile
ps
man pages can be visited for all commands. docker network create man page is man docker-network-create. instead of spaces separate commands with -.
0 notes
leocat-blog · 8 years ago
Text
[Docker] RUN vs CMD vs ENTRYPOINT in Dockerfile
헷갈리기 쉬운 Docker Dockerfile 명령어, RUN, CMD, ENTRYPOINT. 모두 뭔가 실행하는 명령어이다.
RUN. 새로운 레이어에서 명령어를 실행하고, 새로운 이미지를 생��한다. 보통 패키지 설치 등에 사용된다. e.g. apt-get
CMD. default 명령이나 파라미터를 설정한다. docker run 실행 시 실행할 커맨드를 주지 않으면 이 default 명령이 실행된다. 그리고 ENTRYPOINT의 파라미터를 설정할 수도 있다. CMD의 주용도는 컨테이너를 실행할 때 사용할 default를 설정하는 것이다.
ENTRYPOINT. 컨테이너를 실행할 수 있게 설정한다.
RUN
보통 이미지 위에 다른 패키치(프로그램)를 설치하고 새로운 레이어를 생성할 때 사용한다. 다음은 ubuntu 이미지 위에 curl을 설치하는 예제이다.
FROM ubuntu:14.04 RUN apt-get update RUN apt-get install -y curl
RUN 명령을 실행할 때 마다 레이어가 생성되고 캐시된다. 따라서, 위와 같이 RUN 명령을 따로 실행하면 apt-get update는 다시 실행되지 않아서 최신 패키지를 설치할 수 없다. 아래처럼 RUN 명령 하나에 apt-get update와  install을 함께 실행해 주자.
FROM ubuntu:14.04 RUN apt-get update && apt-get install -y \     curl \     nginx \ && rm -rf /var/lib/apt/lists/*
CMD
CMD는 docker run 실행 시 명령어를 주지 않았을 때 사용할 default 명령을 설정하거나, ENTRYPOINT의 default 파라미터를 설정할 때 사용한다. CMD 명령의 주용도는 컨테이너를 실행할 때 사용할 default를 설정하는 것이다. CMD 명령은 3가지 형태가 있다.
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)
FROM ubuntu CMD echo "This is a test."
위와 같이 Dockerfile을 만들었을 때, docker run 실행 시 아무런 커맨드를 주지 않으면 CMD 명령이 실행된다.
$ docker run -it --rm <image-name> This is a test $
echo “Hello” 라고 커맨드를 주게 되면, CMD는 무시되고 커맨드가 실행된다.
$ docker run -it --rm <image-name> echo “Hello” Hello $
CMD는 여러번 사용할 수 있지만 가장 마지막에 있는 CMD 딱 1개만 남게 된다. (override) ENTRYPOINT의 default 파라미터는 아래 ENTRYPOINT에서..
ENTRYPOINT
ENTRYPOINT는 2가지 형태를 가지고 있다.
ENTRYPOINT ["executable", "param1", "param2"] (exec form, preferred)
ENTRYPOINT command param1 param2 (shell form)
docker run 실행 시 실행되는 명령이라고 생각해도 좋을 것 같다.
FROM ubuntu ENTRYPOINT ["/bin/echo", "Hello"] CMD ["world"]
위 Dockerfile의 내용을 실행하면 CMD 에서 설정한 default 파라미터가 ENTRYPOINT 에서 사용된다. docker run 명령 실행 시 파라미터를 주면 CMD에서 설정한 파라미터는 사용되지 않는다.
$ docker run -it --rm <image-name> Hello world $ docker run -it --rm <image-name> ME Hello ME $
shell form 으로 실행해야만 변수 등이 대체(substitution)된다.
FROM ubuntu ENTRYPOINT [ "echo", "$HOME" ]
$ docker run -it --rm <image-name> $HOME $
위처럼 exec form으로 사용하면 $HOME 이 그대로 사용되고, 아래처럼 shell form으로 사용하면 변수 등이 변환된다.
FROM ubuntu ENTRYPOINT echo $HOME
$ docker run -it --rm <image-name> /root $
CMD와 ENTRYPOINT의 조합은 ENTRYPOINT / CMD combinations에 표로 잘 정리되어 있다.
- 참고 http://goinbigdata.com/docker-run-vs-cmd-vs-entrypoint/ https://docs.docker.com/engine/reference/builder/ https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/
0 notes