Skip to content

Instantly share code, notes, and snippets.

@niktekusho
Last active August 23, 2018 15:55
Show Gist options
  • Save niktekusho/6d6f170fa0fc03693b2f7226891cc745 to your computer and use it in GitHub Desktop.
Save niktekusho/6d6f170fa0fc03693b2f7226891cc745 to your computer and use it in GitHub Desktop.
A dockerode example using ES7 features. The script creates and starts a MongoDB container, then waits for 10 seconds and finally stops and deletes the container.
const Docker = require('dockerode');
const localDocker = new Docker();
async function setup(hostPort) {
const mongoContainer = await localDocker.createContainer({
Image: 'mongo:4.0.0',
Hostconfig: {
PortBindings: {
'27017/tcp': [{
HostPort: hostPort,
}],
},
},
AttachStdin: false,
AttachStdout: true,
AttachStderr: true,
Tty: true,
OpenStdin: false,
StdinOnce: false
});
return mongoContainer;
}
// Important: port MUST BE a string (Error: json: cannot unmarshal number into Go struct field PortBinding.HostPort of type string)
setup('12345')
.then(container => container.start())
.then((container) => {
return new Promise(resolve => setTimeout(() => resolve(container), 10 * 1000));
})
.then(container => container.stop())
.then(container => container.remove())
.catch(err => console.error(err));
@niktekusho
Copy link
Author

niktekusho commented Aug 23, 2018

setup()
	.then(container => container.start())
	...
	.catch(err => console.error(err));

is needed since as of version 10.9.0 Node doesn't support aync/await syntax at the top level code block. 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment