bitstream/routes/containers.js

102 lines
2.8 KiB
JavaScript

// containers.js
const express = require('express');
const router = express.Router();
const containerService = require('../docker/containerService');
// List all containers
router.get('/', async (req, res) => {
try {
const containers = await containerService.listContainers();
res.json(containers);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch containers' });
}
});
// Get container stats
router.get('/:id/stats', async (req, res) => {
try {
const stats = await containerService.getContainerStats(req.params.id);
res.json(stats);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch container stats' });
}
});
// Start container
router.post('/:id/start', async (req, res) => {
try {
await containerService.startContainer(req.params.id);
res.json({ message: 'Container started successfully' });
} catch (error) {
res.status(500).json({ error: 'Failed to start container' });
}
});
// Stop container
router.post('/:id/stop', async (req, res) => {
try {
await containerService.stopContainer(req.params.id);
res.json({ message: 'Container stopped successfully' });
} catch (error) {
res.status(500).json({ error: 'Failed to stop container' });
}
});
// Restart container
router.post('/:id/restart', async (req, res) => {
try {
await containerService.restartContainer(req.params.id);
res.json({ message: 'Container restarted successfully' });
} catch (error) {
res.status(500).json({ error: 'Failed to restart container' });
}
});
// Create and run new container
router.post('/create', async (req, res) => {
try {
const { name, image, ports = {}, environment = [], volumes = [], restart = 'unless-stopped' } = req.body;
const createOptions = {
Image: image,
name: name,
Env: environment,
HostConfig: {
PortBindings: ports,
Binds: volumes,
RestartPolicy: { Name: restart }
},
ExposedPorts: Object.keys(ports).reduce((acc, port) => {
acc[port] = {};
return acc;
}, {})
};
const id = await containerService.createContainer(createOptions);
res.json({ id, message: 'Container created and started successfully' });
} catch (error) {
res.status(500).json({ error: 'Failed to create container' });
}
});
// Delete container
router.delete('/:id', async (req, res) => {
try {
await containerService.removeContainer(req.params.id);
res.json({ message: 'Container deleted successfully' });
} catch (error) {
res.status(500).json({ error: 'Failed to delete container' });
}
});
// Get container logs
router.get('/:id/logs', async (req, res) => {
try {
const logs = await containerService.getContainerLogs(req.params.id);
res.json({ logs });
} catch (error) {
res.status(500).json({ error: 'Failed to fetch logs' });
}
});
module.exports = router;