Understanding Containerization

Learn the basics of containerization and docker. Understand why everyone is talking about it and how to start with your own container.

Containers stacked on top of each other

What are containers?

In the software world you will always have the problem that one machine is not equal to another machine. Even if two developers have the same computer. Suddenly one has a tool installed which the other one does not have or they have different versions of the tool. So creating a similar environment is hard. Now imagine having this problem on a server. Maybe one has 2 GB of RAM while the other has 4 GB of RAM. Suddenly there are more different factors that play a role in how you run a software.

That is why we have containers. Containers provide you with a reproducable environment. They all start with a base linux image, meaning its like a full operating system, just smaller.

A sample Dockerfile

You can use preexisting Dockerfiles or write your own. Here is a basic Dockerfile for serving some HTML files. This is more or less as simple as it gets.

    
      
FROM node:lts AS build

WORKDIR /app

COPY package.json ./
COPY yarn.lock ./
RUN yarn install
COPY . .
RUN yarn build

FROM nginx:alpine AS runtime
COPY ./nginx/nginx.conf /etc/nginx/nginx.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 8080
    
  

Lets get down to it:

  • FROM node:lts AS build
    • This is your working base image. There are many base images to choose from. All differ from what is inside. You can even create your own base image to use as a starting point.
    • In a typical case you will chose a lightweight linux distro to have a base system with some utilities and then go from there.
  • WORKDIR /app
    • This specifies where all files you interact with (copy, generate, etc.) will be stored.
  • COPY Command
    • The copy command allows you to copy files from your one place to another. This might be from your local project source inside your container to use.
  • RUN Command
    • The run command allows you to basically run commands. So if you would run on your local machine yarn build, you would do the same with run.
  • EXPOSE Command
    • The expose command tells docker which ports to make available on the container for you to use.
    • This would typically be your ports which your applications listens on.