Configuring a container

edit

A ContainerDefinition describes a container: its image, its command, its environment, its ports, its mounts, and what "ready" means. CreateContainer turns it into a TemporaryContainer, which creates the container when you call StartAsync and removes it when you dispose it.

var definition = new ContainerDefinition(ImageSource.FromRegistry("redis:8"));
definition.Environment.Add("TZ", "UTC");
definition.Ports.Add(new ContainerPort(6379));
definition.WaitStrategies.Add(Wait.ForPort(6379));

await using var container = definition.CreateContainer();
await container.StartAsync();

A few rules hold for every setting:

  • The container owns a copy. CreateContainer copies the definition, so you can change it and create another container from it without affecting the first one. The copy the container owns, container.Definition, is read-only: changing it throws an InvalidOperationException.
  • To start from an existing definition, pass it to the copy constructor, new ContainerDefinition(other). The copy can be changed even when other belongs to a container.
  • Names are generated. A container with neither a Name nor a ReuseId gets a random name, so two containers created from the same definition never collide, and a container whose creation failed can still be found and removed. Set Name only when something outside your code needs to find the container by name.
  • Defaults are safe. Ports are published on the loopback address, and the runtime is detected automatically. See Ports and Container runtimes.

Pages of this group

  • Images: run an image from a registry, a Dockerfile, an archive or the local machine, and decide when it is pulled.
  • Command, environment and resources: the entrypoint, the command, the environment variables, the user, the labels, the resource limits and the network.
  • Ports: publish the ports of the container and find the host port they were given.
  • Volumes and mounts: share files with the host or between containers.
  • Wait strategies: decide when StartAsync considers the container ready.
  • Networks: create a temporary network and connect containers to several networks, with aliases.
  • Advanced options: capabilities, extra hosts, shared memory, ulimits, healthchecks, the stop signal, and the options the definition does not have.