Dockerfiles
Docker isn’t only useful for running other people’s software; it’s also a great way to build and package our own software.
Docker images are built from Dockerfiles. A Dockerfile is a text file that contains all the commands needed to assemble an image. It’s essentially “Infrastructure as Code” (IaC) for an image. It runs commands from top to bottom, kind of like a shell script.
Instead of manually installing dependencies on servers, we can check a Dockerfile into source control and build it automatically.
Your First Dockerfile
Create a file called Dockerfile in your working directory and add these lines:
# Use a lightweight debian os as the base image
FROM debian:stable-slim
# execute the 'echo "hello world"' command when the container runs
CMD ["echo", "hello world"]
Building the Image
Build a new image from the Dockerfile and tag it (-t) with the name helloworld:
docker build . -t helloworld:latest
The -t flag tags the image with the name “helloworld” and the “latest” tag.
Running the Image
Run your image in a new container:
docker run helloworld
You should see “hello world” printed to the console! If you run docker ps, you’ll notice the container is no longer running. It just printed and exited. Containers can execute simple commands that exit quickly, or they can run persistent servers. It depends on the command you give it.