Cloud & Data Centers

Virtual Machines vs. Containers

Compare how virtual machines and containers isolate software, what each costs in overhead and security, and when to use which.

Key takeaways

  • A virtual machine runs a full guest operating system on virtualized hardware managed by a hypervisor.
  • A container is an isolated process, or group of processes, that shares the host kernel and ships with its own libraries.
  • Containers are smaller and quicker to start, which suits frequent deployment and many small services.
  • Virtual machines provide stronger isolation and can run a different operating system from the host.
  • Many production systems combine them by running containers on top of virtual machines.

A virtual machine imitates a whole computer, so it runs its own complete operating system. A container packages one application with its libraries and shares the host's operating system kernel. That single difference explains why containers start faster and weigh less, and why virtual machines draw a stronger boundary between workloads.

Neither replaces the other. Most cloud container platforms actually run containers inside virtual machines, getting the benefits of both. This guide shows how each works and how to choose.

How a virtual machine works

A hypervisor is software that creates and runs virtual machines. It gives each one a set of virtual hardware: processors, memory, disks and network cards. Inside that virtual machine, a guest operating system boots just as it would on a physical computer, and your applications run on top of it.

Hypervisors come in two general styles. One kind runs directly on the physical hardware and is used on servers and in cloud data centers. The other runs as a program on your desktop operating system, which is handy for testing another system on a laptop. Modern processors include virtualization features that let guest code run at close to native speed.

Because each virtual machine carries its own kernel (the core of the operating system that manages hardware and processes), you can run Windows and several Linux distributions side by side on one host. The cost is that each guest needs memory and disk for its operating system, takes time to boot and must be patched like any other computer.

How a container works

A container isn't a small computer. It is an ordinary process that the host operating system fences off. On Linux, two kernel features do most of the work. Namespaces give a process its own view of things such as process IDs, network interfaces and the file system. Control groups, usually called cgroups, limit how much processor time, memory and input/output it can use.

The application's files come from a container image, a read-only bundle containing the program, its libraries and default settings. When you start a container, the system adds a thin writable layer on top. Delete the container and that layer goes with it.

Two ways to isolate an application
Virtual machine Own guest operating system and kernel Virtual hardware from a hypervisor Boots like a computer Can run a different OS than the host Stronger boundary between tenants Container Shares the host kernel Isolated by operating system features Starts about as fast as a process Must be compatible with the host kernel Lighter, with a thinner boundary VS Virtual machine Own guest operating system and kernel Virtual hardware from a hypervisor Boots like a computer Can run a different OS than the host Stronger boundary between tenants Container Shares the host kernel Isolated by operating system features Starts about as fast as a process Must be compatible with the host kernel Lighter, with a thinner boundary

Since Linux containers need a Linux kernel, tools that run them on Windows or macOS quietly start a lightweight Linux virtual machine and put the containers inside it. Windows containers also exist and need a Windows host.

Images, registries and layers

A container image is usually built from a recipe file. Here is a small, representative example for a web service written in Python.

FROM python:3-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
USER 1000
CMD ["python", "app.py"]

Each instruction contributes to the image, and many of them create a layer that can be cached and reused. If you change only your application code, the dependency layer doesn't need rebuilding. Finished images are pushed to a registry, a server that stores and distributes them. Any machine with a compatible runtime can pull the same image and run it.

This is the main reason developers like containers. The thing tested on a laptop is the same bundle that runs in production, which reduces "it works on my machine" problems. It doesn't remove them entirely: processor architecture, configuration and external services can still differ.

The Open Container Initiative maintains common specifications for images and runtimes, so images built with one tool generally run with another.

From source to running container

A typical delivery pipeline follows a short, repeatable path.

How a containerized change reaches users
1 Write code and a build file The recipe names a base image and the steps to add your app. 2 Build an image A tool assembles layers into one versioned bundle. 3 Test and scan Automated tests run, and dependencies are checked for known flaws. 4 Push to a registry The tagged image is stored where servers can fetch it. 5 Run containers Hosts pull the image and start as many copies as needed. 6 Replace, don't patch To update, build a new image and swap the old containers out. Write code and a build file The recipe names a base image and the steps to add your app. 1 Build an image A tool assembles layers into one versioned bundle. 2 Test and scan Automated tests run, and dependencies are checked for known flaws. 3 Push to a registry The tagged image is stored where servers can fetch it. 4 Run containers Hosts pull the image and start as many copies as needed. 5 Replace, don't patch To update, build a new image and swap the old containers out. 6

That last step reflects a habit often called immutable infrastructure. Instead of logging into a running container to fix it, you change the recipe and deploy a fresh one. Automating this path is the subject of continuous integration and delivery.

Resource use and speed

A virtual machine reserves memory for a whole operating system before your application does anything. Containers add little beyond the application itself, so a given server can usually hold many more of them than virtual machines. Starting a container mostly means starting a process, while a virtual machine has to boot.

Real gains depend on the workload. A large database that needs most of a server benefits little from being packed densely. Dozens of small web services benefit a lot. Without limits, one container can still starve its neighbors, so set processor and memory limits deliberately.

Security differences

The boundary around a virtual machine is the hypervisor, which exposes a relatively narrow interface to guests. Containers share a kernel, which has a much larger surface. A serious kernel flaw could let code escape a container and affect the host or other containers. For untrusted code or unrelated customers, providers typically separate workloads with virtual machines, including very small ones designed to start quickly.

Good habits narrow the gap:

  • Run processes inside containers as a non-administrator user.
  • Avoid privileged mode and don't mount sensitive host directories unless you truly must.
  • Use small, trusted base images and rebuild them regularly to pick up fixes.
  • Never bake passwords or keys into an image, because anyone who can pull it can read them.
  • Keep the host operating system patched.

Virtual machines need the same care inside the guest. Isolation protects neighbors; it doesn't fix a weak password or an unpatched web application.

Where data goes

Containers are designed to be disposable, so anything written inside one disappears when it's removed. Persistent data belongs in a volume (storage managed outside the container's life) or in an external database or object store. Object, block and file storage explains the options. Virtual machines more naturally keep data on attached disks, though you should still treat the machine as replaceable and back up the data separately.

Networking between them

Both technologies give workloads their own network identity, in different ways. A virtual machine gets a virtual network card connected to a virtual switch. It usually receives an IP address of its own and can be managed much like a physical server, with its own firewall and remote login.

A container commonly sits on a private network that exists only inside its host. To reach it from outside, you publish a port: traffic arriving on a chosen port of the host is forwarded to a port inside the container. With the Docker command-line tool, for instance, the following runs a web server and makes it reachable on port 8080 of the host.

docker run --rm -d -p 8080:80 nginx

The -p 8080:80 part maps host port 8080 to container port 80. On a shared or internet-facing machine, think about which addresses that published port listens on, because it may be reachable by more people than you expect. Writing -p 127.0.0.1:8080:80 limits it to the host itself.

Containers across several hosts need an extra networking layer so they can find each other, which orchestration tools provide.

Day-to-day operations

The two styles lead to different routines. With virtual machines, you tend to maintain long-lived systems: schedule operating system updates, watch disk usage, take snapshots before risky changes and reboot when needed. A snapshot captures a machine's state at a moment and makes rollback easy, but it normally depends on the same storage as the machine, so it doesn't count as a full backup.

With containers, you maintain images and definitions. Updating means rebuilding from a newer base image and redeploying. Troubleshooting leans on logs sent outside the container, since the container you want to inspect may already be gone. Teams also have to keep track of many small versioned pieces, which calls for sensible naming and cleanup of old images.

Licensing can differ as well. Commercial operating systems and applications often have specific terms for virtual machines and containers, so check them before multiplying copies.

Choosing between them

Need Better starting point
Run a different operating system Virtual machine
Move an old application with unusual setup Virtual machine
Isolate untrusted or separate tenants Virtual machine
Deploy many small services often Containers
Give every developer an identical environment Containers
Run a desktop application with full OS features Virtual machine

If you have one or two simple applications, containers may add tooling you don't need. A managed platform service could run your code without asking you to think about either. Once you run many containers across several machines, you'll want something to schedule and restart them, which is what Kubernetes does.

Common questions

Are containers just lightweight virtual machines?

No. The shorthand is tempting, but a container has no kernel of its own and no virtual hardware. Treating it like a small server leads to mistakes such as storing data inside it.

Can I run a container inside a virtual machine?

Yes, and it's very common. The virtual machine provides the isolation and the container provides the packaging.

Do containers work for home projects?

They can make self-hosted software easier to install, update and remove. You still need to keep images current and back up the volumes that hold your data.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in Cloud & Data Centers →

Latest news on this topic