Reuse container by name

This commit is contained in:
wancat committed 2023-07-15 15:22:19 +08:00
1 parent e3d66709e4
commit df12fee39c
2 files changed
+11 -7

No files matched your search

+9 -5
View File
@@ -13,15 +13,19 @@ const containerOptions = {
StdinOnce: false,
}
export async function createContainer() {
export async function getOrCreateContainer(name) {
try {
const container = await engine.createContainer(containerOptions)
const container = engine.getContainer(name)
await container.inspect()
return container
} catch (error) {
const container = await engine.createContainer({
...containerOptions,
name,
})
await container.start()
console.log(container.id)
return container
} catch (error) {
console.error(error)
throw error
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
import express from 'express'
import http from 'http'
import { Server } from 'socket.io'
import { createContainer, attachContainer } from './docker.js'
import { getOrCreateContainer, attachContainer } from './docker.js'
const app = express()
const server = http.createServer(app)
@@ -9,7 +9,7 @@ const io = new Server(server)
io.on('connection', async (socket) => {
console.log('Connected to the client.')
const container = await createContainer()
const container = await getOrCreateContainer('odyssey-test')
const stream = await attachContainer(container)
stream.on('data', (chunk) => {