Docker build and Docker run commands
In this post, let’s discus about docker run command and build command and their options.
Docker build command
Docker build command is used to build an image using a Dockerfile. Basic build command is as follows which will execute the Dockerfile in the project directory and do whatever instructions from the current directory files.
docker build .
In some cases there are several Dockerfiles in the project folder as follows.
- Dockerfile.dev
- Dockerfile
In the above case it is important to define which file is taking for build process and if not docker will take the Dockerfile as default one. To define the file name “-f” flag has to be used as follows.
docker build -f Dockerfile.dev .
Even you executes the above code it will make and image which have a name which consists of alphanumeric characters and in all the cases it is hard to remember. Then there should be way to name the image which is tagging.
There is a convention to tag an image as follows and the version is optional to add. If version is not defined it takes as the latest.
<docker_username>/<application_name>:version
Let’s tag an image and for that we use “-t” flag.
docker build -t yashodperera/myapp:beta .
Docker run command
After building the image there are several options we have to add when we running an image and basic command is as follows.
docker run <image>
Image can be identify from the id or form the name if we tagged it.
When we run an image it will create an instance of an image which is known as a container. Container runs and terminate when the process is completed but it remained even after termination. We can remove the container after terminate using “-rm” flag.
docker run -rm <image>
If some application run in a container exposing a port we have to map those ports to local ports to access as follows using “-p” flag.
docker run -p <local_machine_port>:<container_port> <image>
In docker we have to attach volumes to containers. There are three types of volumes and I will explain those in another post deeply for now lets take a simple example where we map host volume using “-v” flag
docker run -v <host_path>:<conatiner_path> <image>
In some cases we have to run the container in background using “-d” flag as follows.
docker run -d <image>
Those are the basic options of docker run command and docker build command.
If you have found this helpful please hit that 👏 and share it on social media :)