Skip to content

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:

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:

shell
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:

sh
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:

sh
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:

sh
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.:

sh
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:

sh
docker push myusername/myapp:1.0