Docker Cheat Sheet Source - Final Draft
Docker Cheat Sheet Source - Final Draft
Introduction
Containers allow the packaging of your application (and everything that you need to runit)ina
"container image". Inside a container you can include a base operationalsystem,libraries,files
andfolders,environmentvariables,volumesmountpoints,andtheapplicationbinaries.
Once a container is created, the execution is managed by the "Docker Engine" aka "Docker
Daemon". You can interact with the the Docker Engine through the "docker" command. These
threeprimarycomponentsofDocker(client,engineandregistry)arediagramedbelow:
DockerEngine
Containerrelatedcommands
docker[CMD][OPTS]CONTAINER
Examples:
AllexamplesprovidedhereworkinRHEL
1. Runacontainerininteractivemode:
$dockerrunitrhel7/rhelb
ash #Runabashshellinsideanimage
[root@.../]#cat/etc/redhatrelease #Checkthereleaseinsidecontainer
2. Runacontainerindetachedmode:
$dockerrunnamemywildflydp8080:8 080jboss/wildfly
3. Runadetachedcontainerinapreviouslycreateddockernetwork:
$dockernetworkcreatemynetwork
$dockerrunnamemywildflynetdnetmynetworkp8080:8 080jboss/wildfly
4. Runadetachedcontainermountingalocalfolderinsidethecontainer:
$dockerrunnamemywildflyvolumed\
vmyfolder/:/opt/jboss/wildfly/standalone/deployments/\
p8080:8 080jboss/wildfly
5. Followthelogsofaspecificcontainer
$dockerlogsfmywildfly
$dockerlogsf<containername>
6. Listcontainers
$dockerps #Listonlyactivecontainers
$dockerpsa #Listallcontainers
7. Stopacontainer
$dockerstop< containername> #Stopacontainer
$dockerstopt1<containername> #Stopacontainer(timeout=1second)
8. Removeacontainer
$dockerrm<
containername> #Removeastoppedcontainer
$dockerrmf<containername> #Removeastoppedcontainer.Forcestopifitisactive
$dockerrmf$(dockerpsaq) #Removeallcontainers
$dockerrm$(dockerpsqf"status=exited)#Removeallstoppedcontainers
9. Executeanewprocessinanexistingcontainer
$dockerexecitmywildflyb
ash #ExecutesandaccessbashinsideaWildFlycontainer
$dockerexecit<containername>< process>
daemon Runthepersistentprocessthatmanagescontainers
attach Attacharunningcontainertoviewitsongoingoutputortocontrolit
interactively
commit Createanewimagefromacontainerschanges
cp Copyfiles/foldersbetweenacontainerandthelocalfilesystem
create Createanewcontainer
diff Inspectchangesonacontainersfilesystem
exec Runacommandinarunningcontainer
export Exportthecontentsofacontainersfilesystemasa.tararchive
kill KillarunningcontainerusingSIGKILLoraspecifiedsignal
logs Fetchthelogsofacontainer
pause Pauseallprocesseswithinacontainer
port Listportmappings,orlookupthepublicfacingportthatisNATedtothe
PRIVATE_PORT
ps Listallcontainers
rename Renameacontainer
restart Restartacontainer
rm Remove/deleteoneormorecontainers
run Runacommandinanewcontainer
start Startoneormorecontainers
stop StopacontainerbysendingSIGTERMthenSIGKILLafteragrace
period.
top Displaytherunningprocessesofacontainer
unpause Unpauseallprocesseswithinacontainer
update Updateconfigurationofoneormorecontainers
wait Blockuntilacontainerstops,thenprintitsexitcode
Imagerelatedcommands
docker[CMD][OPTS]IMAGE
Examples
1. BuildanimageusingaDockerfile
$dockerbuildt[username/]<imagename>[:tag]<dockerfilepath>#Buildanimage
$dockerbuildtmyimage:latest. #Buildanimagecalledmyimageusingthe
Dockerfileinthesamefolderwherethecommandwasexecuted.
2. Checkthehistoryofanimage
$dockerhistoryjboss/wildfly #Checkthehistoryofthejboss/wildflyimage
$dockerhistory[username/]<imagename>[:tag] #Checkthehistoryofanimage
3. Listtheimages
$dockerimages
4. Removeanimagefromthelocalregistry
$dockerrmi[username/]<imagename>[:tag]
5. Taganimage
$dockertagjboss/wildflym
yimage:v1 #Createsanimagecalled
"myimage"withthetag"v1"fortheimagejboss/wildfly:latest
$dockertag<imagename>< newimagename> #Createsanewimagewith
thelatesttag
$dockertag<
imagename>[:tag][username/]<newimagename>[:newtag] #Createsa
newimagespecifyingthe"newtag"fromanexistingimageandtag.
6. ExportingandImportingandimagetoanexternalfile
$dockersaveo<filename>.tar[username/]<imagename>[:tag]#Exporttheimagetoan
externalfile
$dockerloadi<filename>.tar #Importanimagefromanexternalfile
7. Pushanimagetoaregistry.
$dockerpush[registry/][username/]<imagename>[:tag]
build BuildDockerimagesfromaDockerfile
history Showthehistoryofanimage
images Listimages
import Createanemptyfilesystemimageandimportthecontentsofthetarball
intoit
inspect Returnlowlevelinformationonacontainerorimage
load Loadanimagefroma.tararchiveorSTDIN
pull Pullanimageorarepositoryfromtheregistry
push Pushanimageorarepositorytotheregistry
rmi Removeoneormoreimages
save Saveoneormoreimagestoa.tararchive(streamedtoSTDOUTby
default)
search SearchtheDockerregistryforimages
tag Taganimageintoarepository
Networkrelatedcommands
dockernetwork[CMD][OPTS]
connect Connectsacontainertoanetwork
create Createsanewnetworkwiththespecifiedname
disconnect Disconnectsacontainerfromanetwork
inspect Displaysdetailedinformationaboutonanetwork
ls Listsallthenetworkscreatedbytheuser
rm Deletesoneormorenetworks
Registryrelatedcommands
Defaultishttps://index.docker.io/v1/
login LogintoaDockerregistryserver.Ifnoserverisspecified,thenthe
defaultisused
logout LogoutfromaDockerregistryserver.Ifnoserverisspecifiedthenthe
defaultisused.
Volumerelatedcommands
dockervolume[CMD][OPTS]
create Createavolume
inspect Returnlowlevelinformationonavolume
ls Listvolumes
rm Removeavolume
Relatedcommands
dockerevents Getrealtimeinformationfromtheserver
dockerinfo Displaysystemwideinformation
dockerversion Showthedockerversioninformation
systemctlstatus Checkifthedockerserviceisrunning
docker
Dockerfile
The Dockerfile provides the instructions to build a container image through the `dockerbuildt
[username/]<imagename>[:tag] <dockerfilepath>` command. It starts from a previous existing
Baseimage(throughtheFROMclause)followedbyanyotherneededDockerfileinstructions.
This process is very similar to a compilation of a source code into a binary output, but in this
casetheoutputoftheDockerfilewillbeacontainerimage.
ExampleDockerfile
#UsetheexistingWildFlyimage
FROMjboss/wildfly
#Addanadministrativeuser
RUN/opt/jboss/wildfly/bin/adduser.shadminAdmin#70365silent
#ExposetheAdministrativeport
EXPOSE80809990
#BindtheWildFlymanagementtoallIPaddresses
CMD["/opt/jboss/wildfly/bin/standalone.sh","b","0.0.0.0","bmanagement","0.0.0.0"]
UsingtheexampleDockerfile
#BuildtheWildFlyimage
$d
ockerbuildtm
ywildfly.
#RunaWidFlyserver
$d
ockerrunitp8
080:8080p9
990:9990m
ywildfly
#AccesstheWildFlyadministrativeconsoleandloginwiththe
credentialsadmin/Admin#70365
openhttp://<dockerdaemonip>:9990inabrowser
DockerfileINSTRUCTIONarguments
FROM SetstheBaseimageforsubsequentinstructions
MAINTAINER Setstheauthorfieldofthethegeneratedimages
RUN Executescommandsinanewlayerontopofthecurrentimageand
commitstheresults
CMD Allowedonlyonce(ifmany,thenonlythelastonetakeseffect)
LABEL Addsmetadatatoanimage
EXPOSE InformsDockerthatthecontainerlistensonthespecifiednetworkports
atruntime.
ENV Setsanenvironmentvariable
ADD Copiesnewfiles,directoriesorremotefileURLsintothefilesystemof
thecontainer
COPY Copiesnewfilesordirectoriesintothefilesystemofthecontainer
ENTRYPOINT Allowsyoutoconfigureacontainerthatwillrunasanexecutable
VOLUME Createsamountpointandmarksitasholdingexternallymounted
volumesfromnativehostorothercontainers
USER SetstheusernameorUIDtousewhenrunninganimage
WORKDIR SetstheworkingdirectoryforanyRUN,CMD,ENTRYPOINT,COPY,
andADDcommands
ARG Definesavariablethatuserscanpassatbuildtimetothebuilderusing
buildarg
ONBUILD Addsaninstructiontobeexecutedlater,whentheimageisusedasthe
baseforanotherbuild
STOPSIGNAL Setsthesystemcallsignalthatwillbesenttothecontainertoinitiate
exit.
Example:RunningaWebServerContainer
$mkdirpwww/ Createdirectory(ifitdoesntexist)
$echoServerisup>www/index.html Makeatextfiletoservelater
$dockerrund\ Runprocessinacontainerasadaemon
p8000:8000\ Mapport8000incontainerto8000onhost
name=p
ythonweb\ Namethecontainerpythonweb
v`pwd`/www:/var/www/html\ Mapcontainerhtmltohostwwwdirectory
w/var/www/html\ Setworkingdirectoryto/var/www/html
r
hel7/rhel\ Choosetherhel7/rheldirectory
/
bin/python\ Runthepythoncommandfor
mSimpleHTTPServer8000 AsimpleWebserverlisteningtoport8000
$curl<dockerdaemonip>:8000 Checkthatserverisworking
$dockerps Seethatcontainerisrunning
$dockerinspectp
ython_web|less Inspectthecontainer
$dockerexecitp
ython_webb
ash Opentherunningcontainerandlookin
BachirChihani,Ph.D.:
BachirChihani,Ph.D.holdsanengineeringdegreefromEcole
SuperieuredInformatique(Algeria)aswellasaPhDdegreein
ComputerSciencefromTelecomSudParis(France).Bachirhas
workedasadataengineer,softwareengineer,andresearchengineer
formanyyears.Previously,heworkedasanetworkengineerandgot
aCCNACiscocertification.Bachirhasbeenprogrammingformany
yearsinScala/Spark,JavaEE,AndroidandGo.Hehasakeen
interestinOpenSourcetechnologiesparticularlyinthefieldsof
Automation,DistributedComputingandSoftware/SystemDesignand
helikessharinghisexperiencethroughblogging.
BachirauthoredmanyresearchpapersinthefieldofContextAwarenessandreviewedmany
papersforInternationalconferences.Healsoservedasatechnicalreviewerformanybooks
includingSpringBootinAction(Manning,2016)andUnifiedLogProcessing(Manning,2016).
RafaelBenevides,DirectorofDeveloperExperience
Rafael Benevides is a Director of Developer Experience at Red Hat.
In his current role he helpsdevelopersworldwidetobemoreeffective
in software development, and he also promotes tools and practices
that help them to be more productive. He worked in several fields
including application architecture and design. Besides that, he is a
member of Apache DeltaSpike PMC a Dukes ChoiceAwardwinner
project. And a speaker in conferences like JUDCon, TDC, JavaOne
andDevoxx.Twitter|LinkedIn|rafabene.com