Containerize an application
Containerizing an application involves packaging the application and its dependencies into a Docker image, which can be instantiated as a container.
Create a Dockerfile
The first step is to create a Dockerfile, which defines the base image and the necessary instructions to run the application. Since Dockerfiles were covered in the previous section, we won’t go into detail here. However, here’s a sample Dockerfile:
FROM node:18-alpine
WORKDIR /app
COPY . .
RUN npm install --only=production
EXPOSE 3000
CMD ["node", "server.js"]
Define the Build Context
The build context is the directory where the Docker CLI looks for the files needed to build the image. By default, it includes all files in the specified directory, but you can exclude unnecessary files using a .dockerignore file.
The Dockerfile must be inside the build context so that Docker can access it during the build process.
Example Build Context:
build_context/
├── Dockerfile
├── .dockerignore
├── package.json
├── package-lock.json
├── index.js
└── server.js
Build the Image
Run the following command to build a Docker image from the Dockerfile:
docker build -t myapp:1.0 .
The
.at the end specifies the build context (in this case, it's the current directory).
Run the Container
After building the image, you can run a container using:
docker run -d -p 80:3000 myapp:1.0
Here the port 80 on the host machine is mapped to port 3000 on the container.
Push the Image to a Registry
If you want to share your containerized application, you can push it to a container registry like Docker Hub.
Log in to Docker Registry
To push an image, you first need to log in to the registry using:
docker login <registry domain>
For Docker Hub, you can omit the registry domain as it's the default.
Tag the Image
Before pushing, tag the image with appropriate namespace to match its destination in the registry.:
docker tag myapp:1.0 myusername/myapp:1.0
Push the Image
Push the image using the new tag, to store it in the registry using:
docker push myusername/myapp:1.0
Writing a Dockerfile
A Dockerfile is a text file that contains a set of instructions to automate the creation of Docker images. It defines how an image should be built, including its base image, dependencies, configurations and runtime commands.
Multi-Stage Builds
In a traditional build, all steps - downloading dependencies, compiling code and packaging - happen in a single container. This results in large images containing build tools that are not needed in production.
