-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDocker.js
More file actions
2623 lines (2536 loc) · 92.6 KB
/
Docker.js
File metadata and controls
2623 lines (2536 loc) · 92.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require('rubico/global')
const isString = require('rubico/x/isString')
const identity = require('rubico/x/identity')
const size = require('rubico/x/size')
const defaultsDeep = require('rubico/x/defaultsDeep')
const Transducer = require('rubico/Transducer')
const zlib = require('zlib')
const http = require('http')
const Readable = require('./Readable')
const HTTP = require('./HTTP')
const Archive = require('./internal/Archive')
const querystring = require('querystring')
const split = require('./internal/split')
const join = require('./internal/join')
const isArray = require('./internal/isArray')
const pathJoin = require('./internal/pathJoin')
const has = require('./internal/has')
const filterExists = require('./internal/filterExists')
const createUpdateServiceSpec = require('./internal/createUpdateServiceSpec')
const handleDockerHTTPResponse = require('./internal/handleDockerHTTPResponse')
/**
* @name Docker
*
* @docs
* ```coffeescript [specscript]
* new Docker(options {
* apiVersion: string,
* }) -> docker Docker
* ```
*
* Presidium Docker client for [Docker](https://docs.docker.com/reference/).
*
* Note: the Presidium Docker client connects to the Docker socket. Please use caution when creating production services using the Presidium Docker client, see [How would an attacker gain access to the host machine from within a Docker container?](https://www.google.com/search?hl=en&q=how%20would%20an%20attacker%20gain%20access%20to%20the%20host%20machine%20from%20within%20a%20docker%20container).
*
* Arguments:
* * `options`
* * `apiVersion` - the version of the Docker API. Defaults to `'1.48'`.
*/
class Docker {
constructor(options = {}) {
const agent = new http.Agent({
socketPath: '/var/run/docker.sock',
maxSockets: Infinity,
})
this.apiVersion = options.apiVersion ?? '1.48'
this.http = new HTTP(`http://0.0.0.0/v${this.apiVersion}`, { agent })
}
/**
* @name auth
*
* @docs
* ```coffeescript [specscript]
* auth(options {
* username: string,
* password: string,
* email: string,
* serveraddress: string,
* }) -> data Promise<{
* Status: string,
* IdentityToken: string,
* }>
* ```
*
* Validates credentials for a Docker container registry. If available, gets an identity token for accessing the registry without password.
*
* Arguments:
* * `options` - address used for inter-manager communication that is also advertised to other nodes.
* * `username` - authentication credentials.
* * `password` - authentication credentials.
* * `email` - authentication credentials.
* * `serveraddress` - domain or IP of the registry server.
*
* Return:
* * `data`
* * `Status` - the status message of the authentication
* * `IdentityToken` - a token used to authenticate the user in place of a username and password.
*
* ```javascript
* const docker = new Docker()
*
* const data = await docker.auth({
* username: 'admin',
* password: 'password',
* email: 'test@example.com',
* serveraddress: 'localhost:5000',
* })
* ```
*/
async auth(options) {
const response = await this.http.post('/auth', {
headers: {
'Content-Type': 'application/json',
},
body: pipe(options, [
pick(['username', 'password', 'email', 'serveraddress', 'identitytoken']),
JSON.stringify,
]),
})
const data = await handleDockerHTTPResponse(response)
return data
}
/**
* @name listImages
*
* @docs
* ```coffeescript [specscript]
* module DockerDocs 'https://docs.docker.com/reference/api/engine/version/v1.52/'
*
* listImages() -> data Promise<[
* Id: string,
* ParentId: string,
* RepoTags: Array<string>,
* RepoDigests: Array<string>,
* Created: string, # timestamp in seconds
* Size: number, # bytes
* SharedSize: number, # bytes
* Labels: Object<string>,
* Containers: number,
* Manifests: Array<DockerDocs.ImageManifestSummary>,
* Descriptor: DockerDocs.OCIDescriptor,
* ]>
* ```
*
* Returns a list of Docker images stored on the server.
*
* Arguments:
* * (none)
*
* Return:
* * `data`
* * `Id` - the image ID.
* * `ParentId` - ID of the parent image.
* * `RepoTags` - list of image names and tags in the local image cache that reference the image.
* * `RepoDigests` - list of content-addressable digests of locally available image manifests that the image is referenced from.
* * `Created` - the date and time at which the image was created as seconds since EPOCH (January 1, 1970 at midnight UTC/GMT).
* * `Size` - the total size in bytes of the image including all layers that the image is composed of.
* * `SharedSize` - total size of image layers that are shared between the image and other images. `-1` indicates that this value has not been calculated.
* * `Labels` - object of user-defined key/value metadata.
* * `Containers` - number of containers using this image. Includes both stopped and running containers. `-1` indicates that this value has not been calculated.
* * `Manifests` - list of [image manifests](https://docs.docker.com/reference/cli/docker/manifest/) available in the image. Warning: `Manifests` is experimental and may change at any time without any backward compatibility.
* * `Descriptor` - an object containing digest, media type, and size for the image, as defined in the [OCI Content Descriptors Specification](https://github.com/opencontainers/image-spec/blob/v1.0.1/descriptor.md).
*
* ```javascript
* const docker = new Docker()
*
* const data = await docker.listImages()
* ```
*/
async listImages() {
const response = await this.http.get('/images/json')
const data = await handleDockerHTTPResponse(response)
return data
}
/**
* @name listContainers
*
* @docs
* ```coffeescript [specscript]
* module DockerDocs 'https://docs.docker.com/reference/api/engine/version/v1.52/'
*
* listContainers() -> data Promise<[
* Id: string,
* Names: Array<string>,
* Image: string,
* ImageID: string,
* ImageManifestDescriptor: DockerDocs.OCIDescriptor,
* Command: string,
* Created: string, # timestamp in seconds
* Ports: DockerDocs.PortSummary,
* SizeRw: number,
* SizeRootFs: number,
* Labels: Object<string>,
* State: 'created'|'running'|'paused'|'restarting'|'exited'|'removing'|'dead',
* Status: string,
* HostConfig: {
* NetworkMode: string,
* Annotations: Object<string>,
* },
* NetworkSettings: {
* Networks: Object<DockerDocs.EndpointSettings>,
* },
* Mounts: Array<DockerDocs.MountPoint>,
* Health: {
* Status: 'none'|'starting'|'healthy'|'unhealthy',
* FailingStreak: number,
* },
* ]>
* ```
*
* Returns a list of Docker containers on the server.
*
* Arguments:
* * (none)
*
* Return:
* * `data`
* * `Id` - the Docker container ID
* * `Names` - the names associated with the Docker container.
* * `Image` - the name or ID of the image used to create the Docker container.
* * `ImageID` - the ID of the image used to create the Docker container.
* * `ImageManifestDescriptor` - an object containing digest, media type, and size for the image used to create the Docker container, as defined in the [OCI Content Descriptors Specification](https://github.com/opencontainers/image-spec/blob/v1.0.1/descriptor.md).
* * `Command` - the command to run when starting the Docker container.
* * `Created` - the date and time at which the image was created as seconds since EPOCH (January 1, 1970 at midnight UTC/GMT).
* * `Ports` - port-mappings for the Docker container.
* * `SizeRw` - the size of files that have been created or changed by the Docker container.
* * `SizeRootFs` - the total size of all files in the read-only layers of the image that are used by the Docker container.
* * `Labels` - object of user-defined key/value metadata.
* * `State` - the state of the Docker container.
* * `Status` - additional human-readable status of the Docker container, e.g. `'Exit 0'`.
* * `HostConfig` - summary of host-specific runtime information of the Docker container.
* * `NetworkSettings` - summary of the Docker container's network settings.
* * `Mounts` - list of mounts used by the Docker container.
* * `Health` - summary of the Docker container's health status.
*
* ```javascript
* const docker = new Docker()
*
* const data = await docker.listContainers()
* ```
*/
async listContainers() {
const response = await this.http.get('/containers/json')
const data = await handleDockerHTTPResponse(response)
return data
}
/**
* @name pullImage
*
* @docs
* ```coffeescript [specscript]
* module stream 'https://nodejs.org/api/stream.html'
*
* pullImage(
* name string,
* options {
* repo: string,
* tag: string,
* message: string,
* platform: string, # '<os>[/arch[/variant]]'
* username: string,
* password: string,
* email: string,
* serveraddress: string,
* identitytoken: string,
* },
* ) -> dataStream Promise<stream.Readable>
* ```
*
* Pulls or imports a Docker image to the server.
*
* Arguments:
* * `name` - name of the image to pull. May include a tag or digest.
* * `options`
* * `repo` - repository name given to the image after it is pulled. May include a tag or digest.
* * `tag` - the tag or digest of the image.
* * `message` - sets the commit message for the pulled image.
* * `platform` - the platform of the image. If present, the Docker daemon checks if the given image is present in the local image cache with the given OS and Architecture instead of the host's native OS and Architecture. If the given image does exist in the local image cache, but its OS and Architecture do not match, a warning is produced.
* * `username` - authentication credentials.
* * `password` - authentication credentials.
* * `email` - authentication credentials.
* * `serveraddress` - domain or IP of the registry server.
* * `identitytoken` - a token used to authenticate the user in place of a username and password.
*
* Return:
* * `dataStream` - a readable stream of the progress of the Docker `pullImage` operation.
*
* ```javascript
* const docker = new Docker()
*
* const pullStream = await docker.pullImage('nginx:1.19')
*
* pullStream.pipe(process.stdout)
* pullStream.on('end', () => {
* console.log('pullImage success')
* })
* ```
*/
async pullImage(name, options = {}) {
const response = await this.http.post(`/images/create?${querystring.stringify({
fromImage: name,
...pick(['repo', 'tag', 'message', 'platform'])(options),
})}`, {
headers: {
'X-Registry-Auth': pipe(options, [
pick([
'username',
'password',
'email',
'serveraddress',
'identitytoken',
]),
JSON.stringify,
Buffer.from,
buffer => buffer.toString('base64'),
]),
},
})
const dataStream = await handleDockerHTTPResponse(response, { stream: true })
return dataStream
}
/**
* @name buildImage
*
* @docs
* ```coffeescript [specscript]
* module stream 'https://nodejs.org/api/stream.html'
*
* buildImage(path string, options {
* image: string,
* ignore: Array<string>,
* archive: Object<
* Dockerfile: content string,
* [filepath string]: content string,
* ...
* >,
* archiveDockerfile: string,
* platform: string, # '<os>[/arch[/variant]]'
* }) -> dataStream Promise<stream.Readable>
* ```
*
* Builds a Docker Image.
*
* Arguments:
* * `path` - parent directory of the build context.
* * `options`
* * `image` - the name and optional tag of the image. If no tag is present, `'LATEST'` is assumed as the value for the tag.
* * `ignore` - filepaths or filenames to ignore when bundling files and directories for the build context.
* * `archive` - an object of filenames and file contents that will be present in the build context.
* * `archiveDockerfile` - the filepath including filename of the Dockerfile, e.g. `'Dockerfiles/Dockerfile2'`. Defaults to `'Dockerfile'`.
* * `platform` - target platform for the build, e.g. `'linux/arm64'`.
*
* Return:
* * `dataStream` - a readable stream of the progress of the Docker `buildImage` operation.
*
* ```javascript
* const docker = new Docker()
*
* const buildStream = await docker.buildImage(__dirname, {
* image: 'my-image',
* archive: {
* Dockerfile: `
* FROM node:15-alpine
* RUN apk add openssh neovim
* EXPOSE 8080
* `,
* },
* })
*
* buildStream.pipe(process.stdout)
* buildStream.on('end', () => {
* console.log('Build success')
* })
* ```
*
* ### Dockerfile Syntax
* ```sh
* HEALTHCHECK \
* [--interval=<duration '30s'|string>] \
* [--timeout=<duration '30s'|string>] \
* [--start-period=<duration '0s'|string>] \
* [--start-interval=<duration '5s'|string>] \
* [--retries=<3|number>]
*
* ENV <key>=<value> ...
*
* EXPOSE <port>/<protocol 'tcp'|'udp'> ...
*
* WORKDIR <path>
*
* VOLUME ["<path>", ...]
* VOLUME <path> ...
*
* USER <user>[:<group>]|<UID>[:<GID>]
*
* ENTRYPOINT ["<command>", "<parameter>", ...]
* ENTRYPOINT <command> <parameter> ...
*
* CMD ["<command>", "<parameter>", ...]
* CMD ["<parameter>", ...]
* CMD <command> <parameter> ...
* ```
*
* References:
* * [Dockerfile](https://docs.docker.com/engine/reference/builder/)
*/
async buildImage(path, options = {}) {
const pack = Archive.tar(path, {
base: options.archive,
ignore: options.ignore ?? ['node_modules', '.git', '.nyc_output'],
})
const compressed = pack.pipe(zlib.createGzip())
const response = await this.http.post(`/build?${querystring.stringify({
dockerfile: options.archiveDockerfile ?? 'Dockerfile',
t: options.image,
forcerm: true,
platform: options.platform ?? '',
})}`, {
body: compressed,
headers: {
'Content-Type': 'application/x-tar',
},
})
const dataStream = await handleDockerHTTPResponse(response, { stream: true })
return dataStream
}
/**
* @name pushImage
*
* @docs
* ```coffeescript [specscript]
* module stream 'https://nodejs.org/api/stream.html'
*
* pushImage(options {
* image: string, # '[<repo>/]<name>:<tag>'
* registry: string,
* authToken: string,
* username: string,
* password: string,
* email: string,
* serveraddress: string,
* identitytoken: string,
* }) -> dataStream Promise<stream.Readable>
* ```
*
* Pushes a Docker image to a registry.
*
* Arguments:
* * `options`
* * `image` - the name, optional repo, and tag of the image.
* * `registry` - the remote registry to which to push the image.
* * `authToken` - a base64-encoded token containing the username and password authentication credentials. Returned from [ECR getAuthorizationToken](/docs/ECR#getAuthorizationToken).
* * `username` - authentication credentials.
* * `password` - authentication credentials.
* * `email` - authentication credentials.
* * `serveraddress` - domain or IP of the registry server.
* * `identitytoken` - a token used to authenticate the user in place of a username and password.
*
* Return:
* * `dataStream` - a readable stream of the progress of the Docker `pushImage` operation.
*
* ```javascript
* const docker = new Docker()
*
* const dataStream = await docker.pushImage({
* image: 'repo/my-image:mytag',
* registry: 'my-registry.io',
* })
* dataStream.pipe(process.stdout)
* dataStream.on('end', () => {
* console.log('Push success')
* })
* ```
*
*/
async pushImage(options = {}) {
const authOptions = pick(options, [
'username',
'password',
'email',
'serveraddress',
'identitytoken'
])
if (options.authToken) {
const decoded = Buffer.from(options.authToken, 'base64').toString('utf8')
const [username, password] = decoded.split(':')
authOptions.username = username
authOptions.password = password
}
const headers = {
'X-Registry-Auth':
Buffer.from(JSON.stringify(authOptions)).toString('base64')
}
const [name, tag] = options.image.split(':')
const remoteImageName = `${options.repository ?? options.registry}/${name}`
const queryParams = `tag=${encodeURIComponent(tag)}`
const response = await this.http.post(
`/images/${remoteImageName}/push?${queryParams}`,
{ headers }
)
const dataStream = await handleDockerHTTPResponse(response, { stream: true })
return dataStream
}
/**
* @name inspectImage
*
* @docs
* ```coffeescript [specscript]
* module DockerDocs 'https://docs.docker.com/reference/api/engine/version/v1.52/'
*
* inspectImage(image string) -> data Promise<{
* Id: string,
* Descriptor: DockerDocs.OCIDescriptor,
* Manifests: Array<Manifest DockerDocs.ImageManifestSummary>,
* RepoTags: Array<string>,
* RepoDigests: Array<string>,
* Comment: string,
* Created: string, # timestamp in seconds
* Author: string,
* Config: DockerDocs.ImageConfig,
* Architecture: string,
* Variant: string,
* Os: string,
* OsVersion: string,
* Size: number, # bytes
* GraphDriver: DockerDocs.DriverData,
* RootFS: {
* Type: string,
* Layers: Array<string>,
* },
* Metadata: {
* LastTagTime: string, # timestamp in seconds
* },
* }>
* ```
*
* Returns low-level information about a Docker image.
*
* Arguments:
* * `image` - the name or ID of the image to inspect
*
* Return:
* * `data`
* * `Id` - the content-addressable ID of an image.
* * `Descriptor` - an object containing digest, media type, and size for the image, as defined in the [OCI Content Descriptors Specification](https://github.com/opencontainers/image-spec/blob/v1.0.1/descriptor.md).
* * `Manifests` - list of [image manifests](https://docs.docker.com/reference/cli/docker/manifest/) available in the image. Warning: `Manifests` is experimental and may change at any time without any backward compatibility.
* * `RepoTags` - list of image names and tags in the local image cache that reference the image.
* * `RepoDigests` - list of content-addressable digests of locally available image manifests that the image is referenced from.
* * `Comment` - optional message that was set when committing or importing the image.
* * `Created` - the date and time at which the image was created as seconds since EPOCH (January 1, 1970 at midnight UTC/GMT).
* * `Author` - the name of the author that was specified when committing the image.
* * `Config` - the configuration of the image. `Config` fields are used as defaults when starting a container from an image.
* * `Architecture` - the CPU architecture that the image runs on.
* * `Variant` - a CPU architecture variant.
* * `Os` - the operating system that the image is built to run on.
* * `OsVersion` - the version of the operating system that the image is built to run on.
* * `Size` - the total size in bytes of the image including all layers that the image is composed of.
* * `GraphDriver` - information about the storage driver that stores the filesystem used by the Docker container and the image.
* * `RootFS` - information about the image's RootFS, including the layer IDs.
* * `Metadata` - additional metadata of the image in the local cache. This information is not part of the image itself.
*
* ```javascript
* const docker = new Docker()
*
* const data = await docker.inspectImage('my-image:example')
* ```
*/
async inspectImage(image) {
const response = await this.http.get(`/images/${image}/json`)
const data = await handleDockerHTTPResponse(response)
return data
}
/**
* @name tagImage
*
* @docs
* ```coffeescript [specscript]
* tagImage(
* sourceImageTag string, # '[<repo>/]<image>:<tag>'
* targetImageTag string, # '[<repo>/]<image>:<tag>'
* ) -> data Promise<{}>
* ```
*
* Creates a Docker image tag that refers to a source Docker image tag.
*
* Arguments:
* * `sourceImageTag` - the source Docker image tag
* * `targetImageTag` - the Docker image tag to create
*
* Return:
* * `data` - empty object.
*
* ```javascript
* const docker = new Docker()
*
* await docker.tagImage('my-image:example', 'my-registry/my-image:example')
* ```
*/
async tagImage(sourceImageTag, targetImageTag) {
const targetImageTagParts = targetImageTag.split(':')
const tag = targetImageTagParts[targetImageTagParts.length - 1]
const repo = targetImageTagParts.slice(0, -1).join(':')
const response = await this.http.post(`
/images/${sourceImageTag}/tag?${querystring.stringify({ repo, tag })}
`.trim())
await handleDockerHTTPResponse(response, { text: true })
return {}
}
/**
* @name removeImage
*
* @docs
* ```coffeescript [specscript]
* removeImage(image string, options? {
* force: boolean,
* noprune: boolean,
* }) -> data Promise<Array<{ Untagged: string }|{ Deleted: string }>>
* ```
*
* Removes a Docker image and any untagged parent images that were referenced by the Docker image from the server. Docker images can't be removed if they have descendant images, are being used by a running container, or are being used by a build.
*
* Arguments:
* * `image` - the name or ID of the image to remove.
* * `options`
* * `force` - if `true`, removes the image even if it is being used by stopped containers or has other tags. If `false`, the operation will error if the image is being used by stopped containers. Defaults to `false`.
* * `noprune` - if `true`, the operation will not delete untagged parent images. If `false`, the operation will delete untagged parent images. Defaults to `false`.
*
* Return:
* * `data`
* * `Untagged` - the image ID of an image that was untagged.
* * `Deleted` - the image ID of an image that was deleted.
*
* ```javascript
* const docker = new Docker()
*
* await docker.removeImage('my-image:example')
* ```
*/
async removeImage(image, options = {}) {
const response = await this.http.delete(`/images/${image}?${
querystring.stringify(pick(options, ['force', 'noprune']))
}`)
const data = await handleDockerHTTPResponse(response)
return data
}
/**
* @name createContainer
*
* @docs
* ```coffeescript [specscript]
* createContainer(options {
* name: string,
* image: string,
* rm: boolean,
* restart: 'no'|'on-failure[:<max-retries>]'|'always'|'unless-stopped',
* logDriver: 'local'|'json-file'|'syslog'|'journald'|'gelf'|'fluentd'|'awslogs'|'splunk'|'etwlogs'|'none',
* logDriverOptions: Object<string>,
* publish: Object<
* [hostPort string]: containerPort string # 8080
* |containerPortWithProtocol string # '<containerPort>[/<"tcp"|"udp"|"sctp">]'
* >,
* healthCmd: Array<string>,
* healthInterval: number, # nanoseconds, minimum 1e6, default 10e9
* healthTimeout: number, # nanoseconds, minimum 1e6, default 20e9
* healthRetries: number, # default 5
* healthStartPeriod: number, # nanoseconds, minimum 1e6
* memory: number, # bytes
* cpus: number,
* mounts: Array<{
* source: string,
* target: string,
* readonly: boolean,
* type: 'bind'|'cluster'|'image'|'npipe'|'tmpfs'|'volume',
* }>|Array<
* mount string, # '<source>:<target>[:<readonly true|false>]'
* >,
*
* # Dockerfile defaults
* cmd: Array<string|number>,
* expose: Array<port string>, # '<port>[/<"tcp"|"udp"|"sctp">]'
* volume: Array<path string>,
* workdir: path string,
* env: Object<string>,
* }) -> data Promise<{
* Id: string,
* Warnings: Array<string>,
* }>
* ```
*
* Creates a Docker container.
*
* Arguments:
* * `options`
* * `name` - the name that will be assigned to the Docker container.
* * `image` - the name and tag of the image.
* * `rm` - automatically remove the Docker container when it exits.
* * `restart` - the restart policy for the Docker container.
* * `logDriver` - the logging driver used for the Docker container.
* * `logDriverOptions` - driver-specific configuration options for the logging driver.
* * `publish` - object of mappings of host ports to container ports with optional protocols.
* * `healthCmd` - a command that checks the health of the Docker container. The health check fails if the command errors. The command is run inside the Docker container.
* * `healthInterval` - time in nanoseconds to wait between healthchecks.
* * `healthTimeout` - time in nanoseconds to wait before the healthcheck fails.
* * `healthRetries` - number of times to retry the health check before the Docker container is considered unhealhty.
* * `healthStartPeriod` - time in nanoseconds to wait when the Docker container starts up before running the first health check command.
* * `memory` - memory limit of the Docker container in bytes.
* * `cpus` - CPU quota in CPUs.
* * `mounts` - specification of the Docker container's volumes or mounts
* * `source` - the mount source (e.g. a volume name or a host path).
* * `target` - the mounted path inside the Docker container.
* * `readonly`- if `true`, the mount is read-only. If `false`, the mount is writable. Defaults to `false`.
* * `type` - the mount type.
* * `cmd` - the command that is run by the Docker container.
* * `expose` - an array of ports with optional protocols that the Docker container exposes.
* * `volume` - an array of mount point paths inside the Docker container.
* * `workdir` - the working directory of the Docker container.
* * `env` - an object of the Docker container's environment variables. Maps environment variable names to environment variable values, e.g. `{ FOO: 'bar' }`.
*
* Return:
* * `data`
* * `Id` - the ID of the Docker container.
* * `Warnings` - warnings encountered when creating the Docker container.
*
* Restart policies:
* * `no` - do not restart the Docker container when it exits
* * `on-failure` - restart only if container exits with non-zero exit code
* * `always` - always restart container regardless of exit code
* * `unless-stopped` - like `always` except if the Docker container was put into a stopped state before the Docker daemon was stopped
*
* Health checks:
* * `[]` - inherit healthcheck from image or parent image
* * `['NONE']` - disable healthcheck
* * `['CMD', ...args]` - exec arguments directly
* * `['CMD-SHELL', command string]` - run command with system's default shell
*
* Mount types:
* * `bind` - mounts a file or directory from the host into the Docker container. The `source` must exist prior to creating the Docker container.
* * `cluster` - a Docker Swarm cluster volume.
* * `image` - mounts a Docker image.
* * `npipe` - mounts a named pipe from the host into the Docker container.
* * `tmpfs` - create a tmpfs with the given options. The `source` cannot be specified with mount type `tmpfs`.
* * `volume` - creates a volume with the given name and options or uses a pre-existing volume with the same name and options. The volume persists when the Docker container is removed.
*
* ```javascript
* const docker = new Docker()
*
* const data = await docker.createContainer({
* image: 'node:15-alpine',
* cmd: ['node', '-e', 'console.log(\'Hello World.\')'],
* rm: true,
* })
* ```
*
*/
async createContainer(options) {
const response = await this.http.post(`/containers/create?${
querystring.stringify({
...options.name && { name: options.name },
})
}`, {
body: JSON.stringify({
AttachStderr: true,
AttachStdout: true,
AttachStdin: false,
Tty: false,
Image: options.image,
...options.cmd && { Cmd: options.cmd },
...options.env && {
Env: Object.entries(options.env)
.map(([key, value]) => `${key}=${value}`),
},
...options.expose && {
ExposedPorts: transform(options.expose, Transducer.map(pipe([
String,
split('/'),
all([get(0), get(1, 'tcp')]),
join('/'),
port => ({ [port]: {} }),
])), {}),
},
...options.workdir && {
WorkingDir: options.workdir,
},
...options.volume && {
Volumes: transform(
options.volume,
Transducer.map(path => ({ [path]: {} })),
{},
),
},
...options.healthCmd && {
Healthcheck: { // note: this is correct versus the healthCmd in createService, which is HealthCheck
Test: ['CMD', ...options.healthCmd],
...all({
Interval: get('healthInterval', 10e9),
Timeout: get('healthTimeout', 20e9),
Retries: get('healthRetries', 5),
StartPeriod: get('healthStartPeriod', 1e6),
})(options),
},
},
HostConfig: {
...options.mounts && {
Mounts: options.mounts.map(pipe([
switchCase([
isString,
pipe([
split(':'),
all({ target: get(0), source: get(1), readonly: get(2) }),
]),
identity,
]),
all({
Target: get('target'),
Source: get('source'),
Type: get('type', 'volume'),
ReadOnly: get('readonly', false),
}),
]))
},
...options.memory && { Memory: options.memory },
...options.cpus && { NanoCpus: options.cpus * 1e9 },
...options.publish && {
PortBindings: map.entries(all([ // publish and PortBindings are reversed
pipe([ // container port
get(1),
String,
split('/'),
all([get(0), get(1, 'tcp')]),
join('/'),
]),
pipe([ // host port
get(0),
String,
HostPort => [{ HostPort }],
]),
]))(options.publish),
},
...options.logDriver && {
LogConfig: {
Type: options.logDriver,
Config: { ...options.logDriverOptions },
},
},
...options.restart && {
RestartPolicy: all({
Name: get(0, 'no'),
MaximumRetryCount: pipe([get(1, 0), Number]),
})(options.restart.split(':')),
},
...options.rm && { AutoRemove: options.rm },
},
}),
headers: {
'Content-Type': 'application/json',
},
})
const data = await handleDockerHTTPResponse(response)
return data
}
/**
* @name attachContainer
*
* @docs
* ```coffeescript [specscript]
* module stream 'https://nodejs.org/api/stream.html'
*
* attachContainer(containerId string, options {
* stdout: boolean,
* stderr: boolean,
* }) -> dataStream Promise<stream.Readable>
* ```
*
* Attaches to a Docker container.
*
* Arguments:
* * `containerId` - the ID of the Docker container.
* * `options`
* * `stdout` - if `true`, `attachContainer` attaches to the Docker container's `stdout`. If `false`, `attachContainer` does not attach to the Docker container's `stdout`. Defaults to `true`.
* * `stderr` - if `true`, `attachContainer` attaches to the Docker container's `stderr`. If `false`, `attachContainer` does not attach to the Docker container's `stderr`. Defaults to `true`.
*
* Return:
* * `dataStream` - a readable stream of the Docker container's `stdout` and/or `stderr`.
*
* ```javascript
* const docker = new Docker()
*
* const data = await docker.createContainer({
* image: 'node:15-alpine',
* cmd: ['node', '-e', 'console.log(\'Hello World.\')'],
* rm: true,
* })
* const containerId = data.Id
*
* const attachStream = await docker.attachContainer(containerId)
* attachStream.pipe(process.stdout) // Hello World.
* attachStream.on('end', () => {
* console.log('Attach success')
* })
*
* await docker.startContainer(containerId)
* ```
*/
async attachContainer(containerId, options = {}) {
const response = await this.http.post(`/containers/${containerId}/attach?${
querystring.stringify({
stream: true,
stdout: Boolean(options.stdout ?? true),
stderr: Boolean(options.stderr ?? true),
})
}`)
const dataStream = await handleDockerHTTPResponse(response, { stream: true })
return dataStream
}
/**
* @name runContainer
*
* @docs
* ```coffeescript [specscript]
* module stream 'https://nodejs.org/api/stream.html'
*
* runContainer(options {
* name: string,
* image: string,
* rm: boolean,
* restart: 'no'|'on-failure[:<max-retries>]'|'always'|'unless-stopped',
* logDriver: 'local'|'json-file'|'syslog'|'journald'|'gelf'|'fluentd'|'awslogs'|'splunk'|'etwlogs'|'none',
* logDriverOptions: Object<string>,
* publish: Object<
* [hostPort string]: containerPort string # 8080
* |containerPortWithProtocol string # '<containerPort>[/<"tcp"|"udp"|"sctp">]'
* >,
* healthCmd: Array<string>,
* healthInterval: number, # nanoseconds, minimum 1e6, default 10e9
* healthTimeout: number, # nanoseconds, minimum 1e6, default 20e9
* healthRetries: number, # default 5
* healthStartPeriod: number, # nanoseconds, minimum 1e6
* memory: number, # bytes
* cpus: number,
* mounts: Array<{
* source: string,
* target: string,
* readonly: boolean,
* type: 'bind'|'cluster'|'image'|'npipe'|'tmpfs'|'volume',
* }>|Array<
* mount string, # '<source>:<target>[:<readonly true|false>]'
* >,
*
* # Dockerfile defaults
* cmd: Array<string|number>,
* expose: Array<port string>, # '<port>[/<"tcp"|"udp"|"sctp">]'
* volume: Array<path string>,
* workdir: path string,
* env: Object<string>,
* }) -> dataStream Promise<stream.Readable>
* ```
*
* Creates, attaches to, and starts a Docker container.
*
* Arguments:
* * `options`
* * `name` - the name that will be assigned to the Docker container.
* * `image` - the name and tag of the image.
* * `rm` - automatically remove the Docker container when it exits.
* * `restart` - the restart policy for the Docker container.
* * `logDriver` - the logging driver used for the Docker container.
* * `logDriverOptions` - driver-specific configuration options for the logging driver.
* * `publish` - object of mappings of host ports to container ports with optional protocols.
* * `healthCmd` - a command that checks the health of the Docker container. The health check fails if the command errors. The command is run inside the Docker container.
* * `healthInterval` - time in nanoseconds to wait between healthchecks.
* * `healthTimeout` - time in nanoseconds to wait before the healthcheck fails.
* * `healthRetries` - number of times to retry the health check before the Docker container is considered unhealhty.
* * `healthStartPeriod` - time in nanoseconds to wait when the Docker container starts up before running the first health check command.
* * `memory` - memory limit of the Docker container in bytes.
* * `cpus` - CPU quota in CPUs.
* * `mounts` - specification of the Docker container's volumes or mounts
* * `source` - the mount source (e.g. a volume name or a host path).
* * `target` - the mounted path inside the Docker container.
* * `readonly`- if `true`, the mount is read-only. If `false`, the mount is writable. Defaults to `false`.
* * `type` - the mount type.
* * `cmd` - the command that is run by the Docker container.
* * `expose` - an array of ports with optional protocols that the Docker container exposes.
* * `volume` - an array of mount point paths inside the Docker container.
* * `workdir` - the working directory of the Docker container.
* * `env` - an object of the Docker container's environment variables. Maps environment variable names to environment variable values, e.g. `{ FOO: 'bar' }`.
*