Class: DockerContainer
A container of the Docker daemon, with its settings and its state as inspected, and its operations: start, stop, restart, pause, kill, remove, update, commit, exec, TTYs, logs, stats and the export of its files. It is not created with new: Docker.getContainer, Docker.listContainers, Docker.createContainer and DockerImage.run return it.
Its properties are a snapshot, taken when it is obtained and refreshed by its own operations (start(), stop(), restart(), pause(), unpause(), kill(), update()): the changes made by others (the container exiting, docker stop) are seen by getting it again. Its operations reject with DockerContainerNotFoundException when the container was removed, with DockerRequestException when the daemon refuses them otherwise (not running: HTTP 409), and with the network error of Node.js when the daemon cannot be reached.
Example
import {type Docker, type DockerContainer, type DockerImage} from 'lakutata/com/docker'
declare const docker: Docker
const image: DockerImage = await docker.getImage('alpine:3.20')
const container: DockerContainer = await docker.createContainer(image.id, {
name: 'worker',
cmd: ['sh', '-c', 'echo started; sleep 3600'],
env: {MODE: 'production'},
ports: [{port: 8080, type: 'tcp', hostPorts: [18080]}],
binds: [{hostPath: '/srv/data', containerPath: '/data', rw: true}],
restartPolicy: 'unless-stopped'
})
await container.start()
console.log(container.state.status, container.ports)
//The exit code, stdout and stderr
const {exitCode, stdout} = await container.exec({cmd: ['ls', '/data']})
console.log(exitCode, stdout)
await container.stop({timeout: 10})
await container.remove()Extends
Constructors
Constructor
new DockerContainer(
cradleProxy):DockerContainer
Called by the container only: an object is created through a container (see the class description), never with new.
Parameters
cradleProxy
Record<string | symbol, any>
The container's resolution proxy.
Returns
DockerContainer
Inherited from
Properties
binds
binds:
ContainerBind[]
The directories and files of the host mounted in the container (the bind mounts; not the volumes).
capabilities
capabilities:
ContainerCapability[]
The kernel capabilities added to the container (--cap-add).
cgroup
cgroup:
string|undefined
The cgroup the container joins (container:<name|id>), as the daemon reports it (an empty string by default).
cgroupParent
cgroupParent:
string|undefined
The parent cgroup under which the container's cgroup is created (an empty string by default).
constructor
constructor:
Function
The initial value of Object.prototype.constructor is the standard built-in Object constructor.
Inherited from
Provider.constructor
cpuSet
cpuSet:
number[]
The indexes of the CPUs the container may run on, sorted; empty for all of them.
createdAt
createdAt:
Time
When the container was created.
devices
devices:
ContainerDevice[]
The devices of the host added to the container.
env
env:
Record<string,string>
The environment variables of the container, the image's included, by name.
hostname
hostname:
string
The host name of the container (its short ID unless set when it was created).
id
id:
string
The full ID of the container (64 hexadecimal characters). It changes when DockerContainer.update recreates the container.
image
image:
DockerImage|undefined
The image the container was created from; undefined when it no longer exists (removed with force while the container was stopped).
memoryLimit
memoryLimit:
number
The memory limit of the container, in bytes; 0 for no limit.
name
name:
string
The name of the container, without the leading / of the Engine API.
networks
networks:
ContainerNetwork[]
The networks the container is connected to, with its addresses in each.
OOMKillDisable
OOMKillDisable:
boolean
Whether the OOM killer is disabled for the container.
pidMode
pidMode:
string|undefined
The PID namespace mode of the container: 'host', 'container:<name|id>', or an empty string for its own.
ports
ports:
ContainerPort[]
The ports of the container, exposed by its image or published: one entry per IP address of the container, port and protocol, with the ports of the host published to it, each one once (empty when not published).
privileged
privileged:
boolean
Whether the container has full access to the host (--privileged).
restartCount
restartCount:
number
How many times the daemon restarted the container, by its restart policy.
restartPolicy
restartPolicy:
ContainerRestartPolicy
When the daemon restarts the container after it exits ('no' by default; 'on-failure:3' for 3 retries at most).
state
state:
ContainerState
The state of the container: its status ('created', 'running', 'exited'…), its process ID, its exit code and its start and finish times.
tty
tty:
boolean
Whether the container's main process has a TTY: its logs are then raw, not split into stdout and stderr.
Accessors
$id
Get Signature
get $id():
string|symbol
The name the object was registered under (its key in the module options), or a symbol of its class for an object registered by its class or built without registration.
Returns
string | symbol
Inherited from
$symbol
Get Signature
get $symbol():
symbol
A symbol unique to the instance (made from its $uuid), created on first read.
Returns
symbol
Inherited from
$uuid
Get Signature
get $uuid():
string
A random UUID identifying the instance.
Returns
string
Inherited from
className
Get Signature
get
staticclassName():string
The name of the class.
Returns
string
Inherited from
className
Get Signature
get className():
string
The name of the object's class.
Returns
string
Inherited from
Methods
[asyncDispose]()
[asyncDispose]():
Promise<void>
Dispose the object at the end of an await using block, as BaseObject.dispose.
Returns
Promise<void>
Resolves once the object is destroyed.
Inherited from
acceptsOption()
staticacceptsOption(name,value):boolean
Whether the class accepts an option which is not one of its @Configurable properties (an option it reads with getConfigurableRecords()): the modules check the options of the objects they declare and warn of the options the classes do not accept. Override it in the classes reading options without configurable properties.
Parameters
name
string
The option name.
value
unknown
The option value.
Returns
boolean
true when the option is accepted; false by default.
Inherited from
assign()
Call Signature
staticassign<T,U>(target,source):T&U
Copy the values of all of the enumerable own properties from one or more source objects to a target object. Returns the target object.
Type Parameters
T
T extends object
U
U
Parameters
target
T
The target object to copy to.
source
U
The source object from which to copy properties.
Returns
T & U
Inherited from
Call Signature
staticassign<T,U,V>(target,source1,source2):T&U&V
Copy the values of all of the enumerable own properties from one or more source objects to a target object. Returns the target object.
Type Parameters
T
T extends object
U
U
V
V
Parameters
target
T
The target object to copy to.
source1
U
The first source object from which to copy properties.
source2
V
The second source object from which to copy properties.
Returns
T & U & V
Inherited from
Call Signature
staticassign<T,U,V,W>(target,source1,source2,source3):T&U&V&W
Copy the values of all of the enumerable own properties from one or more source objects to a target object. Returns the target object.
Type Parameters
T
T extends object
U
U
V
V
W
W
Parameters
target
T
The target object to copy to.
source1
U
The first source object from which to copy properties.
source2
V
The second source object from which to copy properties.
source3
W
The third source object from which to copy properties.
Returns
T & U & V & W
Inherited from
Call Signature
staticassign(target, ...sources):any
Copy the values of all of the enumerable own properties from one or more source objects to a target object. Returns the target object.
Parameters
target
object
The target object to copy to.
sources
...any[]
One or more source objects from which to copy properties
Returns
any
Inherited from
commit()
commit(
options?):Promise<DockerImage>
Create an image from the container's current files, as docker commit.
Parameters
options?
The name of the image (repoTag, repo:tag; none by default) and whether the container is paused while it is committed (pauseBeforeCommitting, true by default).
Returns
Promise<DockerImage>
The image created.
Throws
When the container was removed.
create()
Call Signature
staticcreate(o):any
Creates an object that has the specified prototype or that has null prototype.
Parameters
o
object | null
Object to use as a prototype. May be null.
Returns
any
Inherited from
Call Signature
staticcreate(o,properties):any
Creates an object that has the specified prototype, and that optionally contains specified properties.
Parameters
o
object | null
Object to use as a prototype. May be null
properties
PropertyDescriptorMap & ThisType<any>
JavaScript object that contains one or more property descriptors.
Returns
any
Inherited from
createTTY()
createTTY(
options?):Promise<DockerContainerTTY>
Start an interactive command with a TTY in the running container, as docker exec -it. The command runs until it exits (or its stream is closed): see DockerContainerTTY.
Parameters
options?
The command (['/bin/sh'] by default; the program and its arguments, run as they are, or a command line, run by /bin/sh -c) and the initial console size.
Returns
Promise<DockerContainerTTY>
The TTY, its command started.
Throws
When the container was removed.
Throws
When the container is not running (HTTP 409).
defineProperties()
staticdefineProperties<T>(o,properties):T
Adds one or more properties to an object, and/or modifies attributes of existing properties.
Type Parameters
T
T
Parameters
o
T
Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object.
properties
PropertyDescriptorMap & ThisType<any>
JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property.
Returns
T
Inherited from
defineProperty()
staticdefineProperty<T>(o,p,attributes):T
Adds a property to an object, or modifies attributes of an existing property.
Type Parameters
T
T
Parameters
o
T
Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object.
p
PropertyKey
The property name.
attributes
PropertyDescriptor & ThisType<any>
Descriptor for the property. It can be for a data property or an accessor property.
Returns
T
Inherited from
dispose()
dispose():
Promise<void>
Destroy the object: its beforeDestroy(), the objects it created, then its destroy(). Calling it more than once destroys once. A disposed singleton or scoped object is dropped from its container, which creates a new one on the next request. Using a destroyed object (getObject(), buildObject()) throws an ObjectDestroyedException.
Returns
Promise<void>
Resolves once the object is destroyed.
Throws
The error of the object's own beforeDestroy() or destroy() (an AggregateError when several fail); the errors of the objects it created are reported through the application's logger instead.
Inherited from
entries()
Call Signature
staticentries<T>(o): [string,T][]
Returns an array of key/values of the enumerable own properties of an object
Type Parameters
T
T
Parameters
o
{[s: string]: T; } | ArrayLike<T>
Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
Returns
[string, T][]
Inherited from
Call Signature
staticentries(o): [string,any][]
Returns an array of key/values of the enumerable own properties of an object
Parameters
o
{ }
Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
Returns
[string, any][]
Inherited from
exec()
exec(
options):Promise<ContainerExecResult>
Run a command in the running container, as docker exec (no TTY, no stdin), and wait for it to exit. As the containerd component's, a command exiting with a non-zero code resolves too: check its exitCode.
Parameters
options
The command: a program and its arguments (['ls', '-l']), run as they are, or a command line ('ls /data | wc -l'), run by /bin/sh -c.
Returns
Promise<ContainerExecResult>
The exit code of the command, its stdout and its stderr (a program not found: exit code 127 or 126, the error in the output).
Throws
When the container was removed.
Throws
When the container is not running or paused (HTTP 409).
exportDirectory()
exportDirectory(
options):Promise<void>
Copy a file or a directory out of the container as a tar archive, as docker cp container:path -. The container may be stopped.
Parameters
options
ContainerExportDirectoryOptions
The path in the container, and the destination of the archive: a file path (created or overwritten) or a writable stream (ended after the archive).
Returns
Promise<void>
Throws
When the container was removed.
Throws
When the path is not found in the container (HTTP 404).
Throws
The error of the destination.
freeze()
Call Signature
staticfreeze<T>(f):T
Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
Type Parameters
T
T extends Function
Parameters
f
T
Object on which to lock the attributes.
Returns
T
Inherited from
Call Signature
staticfreeze<T,U>(o):Readonly<T>
Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
Type Parameters
T
T extends object
U
U extends string | number | bigint | boolean | symbol
Parameters
o
T
Object on which to lock the attributes.
Returns
Readonly<T>
Inherited from
Call Signature
staticfreeze<T>(o):Readonly<T>
Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
Type Parameters
T
T
Parameters
o
T
Object on which to lock the attributes.
Returns
Readonly<T>
Inherited from
fromEntries()
Call Signature
staticfromEntries<T>(entries):object
Returns an object created by key-value entries for properties and methods
Type Parameters
T
T = any
Parameters
entries
Iterable<readonly [PropertyKey, T]>
An iterable object that contains key-value entries for properties and methods.
Returns
object
Inherited from
Call Signature
staticfromEntries(entries):any
Returns an object created by key-value entries for properties and methods
Parameters
entries
Iterable<readonly any[]>
An iterable object that contains key-value entries for properties and methods.
Returns
any
Inherited from
getMethod()
getMethod(
name,throwExceptionIfNotFound?): (...args) =>any
Get a method bound to the object, to call it by name.
Parameters
name
string | symbol
The method name or symbol.
throwExceptionIfNotFound?
boolean
Throw when the method does not exist, instead of returning a function doing nothing; false by default.
Returns
The bound method, or a function doing nothing (returning undefined) when it does not exist.
(...args) => any
Throws
When the method does not exist and throwExceptionIfNotFound is true.
Inherited from
getOwnPropertyDescriptor()
staticgetOwnPropertyDescriptor(o,p):PropertyDescriptor|undefined
Gets the own property descriptor of the specified object. An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype.
Parameters
o
any
Object that contains the property.
p
PropertyKey
Name of the property.
Returns
PropertyDescriptor | undefined
Inherited from
Provider.getOwnPropertyDescriptor
getOwnPropertyDescriptors()
staticgetOwnPropertyDescriptors<T>(o): { [P in string | number | symbol]: TypedPropertyDescriptor<T[P]> } &object
Returns an object containing all own property descriptors of an object
Type Parameters
T
T
Parameters
o
T
Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
Returns
{ [P in string | number | symbol]: TypedPropertyDescriptor<T[P]> } & object
Inherited from
Provider.getOwnPropertyDescriptors
getOwnPropertyNames()
staticgetOwnPropertyNames(o):string[]
Returns the names of the own properties of an object. The own properties of an object are those that are defined directly on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions.
Parameters
o
any
Object that contains the own properties.
Returns
string[]
Inherited from
getOwnPropertySymbols()
staticgetOwnPropertySymbols(o):symbol[]
Returns an array of all symbol properties found directly on object o.
Parameters
o
any
Object to retrieve the symbols from.
Returns
symbol[]
Inherited from
Provider.getOwnPropertySymbols
getProperty()
getProperty<
T>(propertyKey,defaultValue?):T
Read an own property of the object.
Type Parameters
T
T = any
Parameters
propertyKey
string
The property name.
defaultValue?
T
The value returned when the object has no own property of this name.
Returns
T
The property value, or the default value.
Inherited from
getPrototypeOf()
staticgetPrototypeOf(o):any
Returns the prototype of an object.
Parameters
o
any
The object that references the prototype.
Returns
any
Inherited from
hasMethod()
hasMethod(
name):boolean
Whether the object has a method of this name or symbol (a function of its class, not an own property).
Parameters
name
string | symbol
The method name or symbol.
Returns
boolean
true when the method exists.
Inherited from
hasOwn()
statichasOwn(o,v):boolean
Determines whether an object has a property with the specified name.
Parameters
o
object
An object.
v
PropertyKey
A property name.
Returns
boolean
Inherited from
hasOwnProperty()
hasOwnProperty(
v):boolean
Determines whether an object has a property with the specified name.
Parameters
v
PropertyKey
A property name.
Returns
boolean
Inherited from
hasProperty()
hasProperty(
propertyKey):boolean
Whether the object has an own property (not a method or accessor of its class) of this name or symbol.
Parameters
propertyKey
string | symbol
The property name or symbol.
Returns
boolean
true when the property exists.
Inherited from
is()
staticis(value1,value2):boolean
Returns true if the values are the same value, false otherwise.
Parameters
value1
any
The first value.
value2
any
The second value.
Returns
boolean
Inherited from
isExtensible()
staticisExtensible(o):boolean
Returns a value that indicates whether new properties can be added to an object.
Parameters
o
any
Object to test.
Returns
boolean
Inherited from
isFrozen()
staticisFrozen(o):boolean
Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object.
Parameters
o
any
Object to test.
Returns
boolean
Inherited from
isPrototypeOf()
isPrototypeOf(
v):boolean
Determines whether an object exists in another object's prototype chain.
Parameters
v
Object
Another object whose prototype chain is to be checked.
Returns
boolean
Inherited from
isSealed()
staticisSealed(o):boolean
Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object.
Parameters
o
any
Object to test.
Returns
boolean
Inherited from
keys()
Call Signature
statickeys(o):string[]
Returns the names of the enumerable string properties and methods of an object.
Parameters
o
object
Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
Returns
string[]
Inherited from
Call Signature
statickeys(o):string[]
Returns the names of the enumerable string properties and methods of an object.
Parameters
o
{ }
Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
Returns
string[]
Inherited from
kill()
kill(
options?):Promise<void>
Send a signal to the container's main process, as docker kill (SIGKILL by default), then refresh its properties.
Parameters
options?
The signal sent: a name ('SIGHUP') or a number (1); SIGKILL by default.
Returns
Promise<void>
Throws
When the container was removed.
Throws
When the container is not running (HTTP 409), or the signal is unknown.
logs()
logs(
options?):Promise<ReadableStream>
Read the logs of the container's main process, as docker logs: stdout and stderr in one stream, in their order (split from Docker's multiplexed format unless the container has a TTY).
Parameters
options?
follow (true by default), since and until (UNIX timestamps in seconds; 0, no bound, by default), timestamps (false by default) and tail (a number of lines from the end; all by default).
Returns
Promise<ReadableStream>
The readable stream of the logs.
Remarks
The logs are followed by default: the stream does not end while the container runs. Pass follow: false for the logs written so far.
Throws
When the container was removed.
pause()
pause():
Promise<void>
Suspend the processes of the container, as docker pause, then refresh its properties.
Returns
Promise<void>
Throws
When the container was removed.
Throws
When it is not running or already paused (HTTP 409).
preventExtensions()
staticpreventExtensions<T>(o):T
Prevents the addition of new properties to an object.
Type Parameters
T
T
Parameters
o
T
Object to make non-extensible.
Returns
T
Inherited from
propertyIsEnumerable()
propertyIsEnumerable(
v):boolean
Determines whether a specified property is enumerable.
Parameters
v
PropertyKey
A property name.
Returns
boolean
Inherited from
propertyNames()
propertyNames():
string[]
The names of the object's own properties (not its class's methods and accessors).
Returns
string[]
The names.
Inherited from
propertySymbols()
propertySymbols():
symbol[]
The symbols of the object's own properties.
Returns
symbol[]
The symbols.
Inherited from
remove()
remove(
options?):Promise<void>
Remove the container, as docker rm -v: its anonymous volumes are removed with it. The object is not refreshed: its other operations then fail with DockerContainerNotFoundException.
Parameters
options?
force kills a running container first (false by default).
Returns
Promise<void>
Throws
When the container was already removed.
Throws
When it is running and force is not set (HTTP 409).
restart()
restart(
options?):Promise<void>
Restart the container, as docker restart: stop it as DockerContainer.stop does (when it runs), then start it; then refresh its properties.
Parameters
options?
The signal sent (the container's stop signal, SIGTERM by default) and the timeout before the kill, in seconds (the container's, 10 by default).
Returns
Promise<void>
Throws
When the container was removed.
Throws
When it fails to start (HTTP 500).
seal()
staticseal<T>(o):T
Prevents the modification of attributes of existing properties, and prevents the addition of new properties.
Type Parameters
T
T
Parameters
o
T
Object on which to lock the attributes.
Returns
T
Inherited from
setProperty()
setProperty(
propertyKey,value):void
Set a property of the object; the value is not validated, even for a @Configurable property.
Parameters
propertyKey
string
The property name.
value
any
The value.
Returns
void
Inherited from
setPrototypeOf()
staticsetPrototypeOf(o,proto):any
Sets the prototype of a specified object o to object proto or null. Returns the object o.
Parameters
o
any
The object to change its prototype.
proto
object | null
The value of the new prototype or null.
Returns
any
Inherited from
start()
start():
Promise<void>
Start the container, as docker start, then refresh its properties. A container already running is left as it is (as the Docker CLI does).
Returns
Promise<void>
Throws
When the container was removed.
Throws
When it fails to start (HTTP 500: a command not found, a port already used).
stats()
stats():
Promise<ContainerStats>
Read the resource usage of the container once, as docker stats --no-stream: CPU, memory, network, block I/O and processes, as the Engine API reports them.
Returns
Promise<ContainerStats>
The statistics.
Throws
When the container was removed.
stop()
stop(
options?):Promise<void>
Stop the container, as docker stop: send its stop signal, wait for it to exit, kill it after the timeout; then refresh its properties.
Parameters
options?
The signal sent (the container's stop signal, SIGTERM by default) and the timeout before the kill, in seconds (the container's, 10 by default). A container already stopped is left as it is (as the Docker CLI does).
Returns
Promise<void>
Throws
When the container was removed.
toLocaleString()
toLocaleString():
string
Returns a date converted to a string using the current locale.
Returns
string
Inherited from
toString()
toString():
string
Returns a string representation of an object.
Returns
string
Inherited from
unpause()
unpause():
Promise<void>
Resume the processes of a paused container, as docker unpause, then refresh its properties.
Returns
Promise<void>
Throws
When the container was removed.
Throws
When it is not paused (HTTP 409).
update()
update(
options):Promise<void>
Change the settings of the container, keeping the others. The memory limit, the CPUs and the restart policy are changed live, as docker update does, and the name by renaming it, the container running on. The other settings (and removing the memory limit or the CPU set, which Docker cannot do live) recreate the container: a new one is created from the old one's whole configuration (its image, command, entrypoint, environment, mounts, networks and their static addresses, the addresses Docker assigned being assigned again), with the settings changed, under a temporary name. Once created (and, when the old one was running, the old one stopped and the new one started), the old one is removed without its volumes and the new one takes its name (and its anonymous volumes, mounted again). The object follows the new container: its id changes.
Parameters
options
The settings changed: memoryLimit, cpuSet and restartPolicy live (the swap limit set to Docker's default with the memory), name by a renaming; hostname, env (replacing the container's variables; the image's are added again), cmd, entrypoint, tty, privileged, ports, binds (replacing the bind mounts, the volumes kept), devices, networks (replacing the networks), capabilities, OOMKillDisable, cgroup, cgroupParent and pidMode by a recreation. The settings absent are kept.
Returns
Promise<void>
Remarks
The old container is kept when the creation or the start of the new one fails (invalid settings, the image removed, a network missing): the new one is removed, the old one started again when it was running, and the call rejects. Its files outside the volumes are not kept by a recreation (commit them first, see DockerContainer.commit). A container removed by Docker when it stops (AutoRemove) cannot be kept.
Throws
When the settings are invalid.
Throws
When the container was removed.
Throws
When the container must be recreated and its image no longer exists.
Throws
When a network of the settings is not found.
Throws
When the daemon refuses the changes: a limit refused (HTTP 400), the name already used (HTTP 409), the new container failing to start (HTTP 500).
valueOf()
valueOf():
Object
Returns the primitive value of the specified object.
Returns
Object
Inherited from
values()
Call Signature
staticvalues<T>(o):T[]
Returns an array of values of the enumerable own properties of an object
Type Parameters
T
T
Parameters
o
{[s: string]: T; } | ArrayLike<T>
Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
Returns
T[]
Inherited from
Call Signature
staticvalues(o):any[]
Returns an array of values of the enumerable own properties of an object
Parameters
o
{ }
Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
Returns
any[]