DevOps · Pleno

Containers e Docker: por que 'funciona na minha máquina' acabou

"Funciona na minha máquina" foi durante anos a frase que encerrava discussões sem resolver problema nenhum. Containers acabaram com ela. Ao empacotar a aplicação junto com tudo de que ela precisa para rodar, o container garante que o ambiente seja o mesmo na sua máquina, no CI e em produção. Docker popularizou essa ideia e virou conhecimento obrigatório para qualquer DevOps pleno.

Container vs máquina virtual

A confusão clássica é achar que container é uma VM leve. A diferença está no que cada um virtualiza. Uma VM emula um computador inteiro, com seu próprio sistema operacional completo. Um container compartilha o kernel do host e isola apenas o que a aplicação precisa — por isso é muito mais leve e rápido.

AspectoContainerMáquina virtual
IsolaProcesso e dependênciasSO completo
KernelCompartilha com o hostPróprio
TamanhoMBsGBs
Tempo de startSegundosMinutos
DensidadeCentenas por hostPoucas dezenas

Imagem vs container

Essa distinção cai em entrevista o tempo todo. A imagem é o molde imutável, o template empacotado e versionado. O container é uma instância em execução dessa imagem. Uma analogia útil: a imagem é a classe, o container é o objeto. De uma mesma imagem você pode subir quantos containers quiser.

O Dockerfile

O Dockerfile é a receita que descreve, passo a passo, como construir a imagem. Cada instrução é declarativa e o resultado é reproduzível:

"It works on my machine" was for years the phrase that ended discussions without solving any problem. Containers put an end to it. By packaging the application together with everything it needs to run, the container guarantees the environment is the same on your machine, in CI and in production. Docker popularized this idea and it became required knowledge for any mid-level DevOps engineer.

Container vs virtual machine

The classic confusion is thinking a container is a lightweight VM. The difference is in what each one virtualizes. A VM emulates an entire computer, with its own full operating system. A container shares the host's kernel and isolates only what the application needs — which is why it's much lighter and faster.

AspectContainerVirtual machine
IsolatesProcess and dependenciesFull OS
KernelShared with the hostIts own
SizeMBsGBs
Start timeSecondsMinutes
DensityHundreds per hostA few dozen

Image vs container

This distinction comes up in interviews all the time. The image is the immutable mold, the packaged and versioned template. The container is a running instance of that image. A useful analogy: the image is the class, the container is the object. From a single image you can start as many containers as you like.

The Dockerfile

The Dockerfile is the recipe that describes, step by step, how to build the image. Each instruction is declarative and the result is reproducible:

FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]

Camadas e cache de build

Cada instrução do Dockerfile gera uma camada, e o Docker reaproveita as camadas que não mudaram (cache). É por isso que, no exemplo acima, copiamos o package.json e rodamos o npm ci antes de copiar o resto do código: enquanto as dependências não mudarem, essa camada cara fica em cache e o build fica muito mais rápido.

Ordene o Dockerfile do que muda menos para o que muda mais. As coisas estáveis (dependências) ficam em cima, o código volátil em baixo — assim o cache trabalha a seu favor.

Registry: onde as imagens vivem

Depois de construída, a imagem é enviada (push) para um registry — Docker Hub, GitHub Container Registry, ECR, etc. É o equivalente a um repositório Git, mas para imagens. O pipeline de CI/CD constrói a imagem, faz push para o registry e os ambientes a baixam (pull) dali.

Layers and build cache

Each Dockerfile instruction generates a layer, and Docker reuses the layers that haven't changed (cache). That's why, in the example above, we copy package.json and run npm ci before copying the rest of the code: as long as the dependencies don't change, that expensive layer stays cached and the build is much faster.

Order your Dockerfile from what changes least to what changes most. Stable things (dependencies) go on top, volatile code at the bottom — that way the cache works in your favor.

Registry: where images live

Once built, the image is pushed to a registry — Docker Hub, GitHub Container Registry, ECR, etc. It's the equivalent of a Git repository, but for images. The CI/CD pipeline builds the image, pushes it to the registry and the environments pull it from there.

docker build -t minha-app:1.2 .
docker push registry.exemplo.com/minha-app:1.2
docker run -p 3000:3000 minha-app:1.2

Ambiente reproduzível do dev até a produção

O ganho central: a mesma imagem que você roda no notebook é a que roda em produção. Versões de runtime, bibliotecas de sistema e configuração viajam junto. Isso elimina a categoria inteira de bugs do tipo "lá funcionava". E é essa portabilidade que torna possível orquestrar containers em larga escala com Kubernetes.

Conclusão

Containers resolveram o problema da reprodutibilidade ao empacotar aplicação e ambiente juntos, leves e portáteis. Entender a diferença entre imagem e container, como o cache de camadas funciona e o papel do registry é o pacote mínimo que um DevOps pleno precisa dominar — e a base sobre a qual orquestradores como o Kubernetes são construídos.

A reproducible environment from dev to production

The central gain: the same image you run on your laptop is the one that runs in production. Runtime versions, system libraries and configuration travel together. This eliminates the entire category of "it worked over there" bugs. And it's this portability that makes it possible to orchestrate containers at scale with Kubernetes.

Conclusion

Containers solved the reproducibility problem by packaging application and environment together, lightweight and portable. Understanding the difference between image and container, how layer caching works and the role of the registry is the minimum package a mid-level DevOps engineer needs to master — and the foundation on which orchestrators like Kubernetes are built.

Leia também

Voltar à trilha