This commit is contained in:
root
2025-09-24 12:08:06 +00:00
parent 9dea25bbef
commit c44d7c7fca
6 changed files with 232 additions and 67 deletions
+37 -4
View File
@@ -1,20 +1,53 @@
# Stage 1: Frontend build # ===============================
# Stage 1: Frontend Build
# ===============================
FROM node:20-alpine AS frontend-build FROM node:20-alpine AS frontend-build
# Arbeitsverzeichnis
WORKDIR /app/frontend WORKDIR /app/frontend
# Nur package.json & package-lock.json kopieren und Dependencies installieren
COPY frontend/package.json frontend/package-lock.json ./ COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci RUN npm ci
# Restliche Frontend-Dateien kopieren
COPY frontend/ ./ COPY frontend/ ./
# Frontend Build erzeugen (statische Dateien)
RUN npm run build RUN npm run build
# ===============================
# Stage 2: Backend + Frontend # Stage 2: Backend + Frontend
# ===============================
FROM node:20-alpine AS runtime FROM node:20-alpine AS runtime
# Arbeitsverzeichnis
WORKDIR /app/backend WORKDIR /app/backend
# Backend Dependencies installieren
COPY backend/package.json backend/package-lock.json ./ COPY backend/package.json backend/package-lock.json ./
RUN npm ci --only=production RUN npm ci --only=production
COPY backend/ ./
COPY --from=frontend-build /app/frontend/dist ./public
# Backend-Code kopieren
COPY backend/ ./
# public leeren
RUN rm -rf ./public/*
# Inhalt von dist inklusive Unterordner direkt nach public kopieren
COPY --from=frontend-build /app/frontend/dist/. ./public/
# Environment
ENV NODE_ENV=production ENV NODE_ENV=production
EXPOSE 4000
# Ports
# Backend intern: 4001
# Frontend exposed: 5173
EXPOSE 5173
# Node User
USER node USER node
# Container startet das Backend (liefert statisches Frontend)
CMD ["node", "index.js"] CMD ["node", "index.js"]
+32 -53
View File
@@ -4,94 +4,82 @@ import https from 'https';
import axios from 'axios'; import axios from 'axios';
import http from 'http'; import http from 'http';
import { Server } from 'socket.io'; import { Server } from 'socket.io';
import path from 'path';
import { fileURLToPath } from 'url';
dotenv.config(); dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express(); const app = express();
app.use(express.json()); app.use(express.json());
const PORT = process.env.PORT || 4000; // Statische Frontend-Dateien ausliefern
app.use(express.static(path.join(__dirname, 'public')));
// SPA-Fallback für React-Router
app.get('*', (req, res, next) => {
if (req.path.startsWith('/api')) return next();
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Backend-Port fix
const PORT = 4001;
// HTTPS Agent für Self-Signed-Zertifikate // HTTPS Agent für Self-Signed-Zertifikate
const agent = new https.Agent({ rejectUnauthorized: false }); const agent = new https.Agent({ rejectUnauthorized: false });
// Axios-Instance für alle Portainer-Requests // Axios-Instance für Portainer
const axiosInstance = axios.create({ const axiosInstance = axios.create({
httpsAgent: agent, httpsAgent: agent,
headers: { "X-API-Key": process.env.PORTAINER_API_KEY }, headers: { "X-API-Key": process.env.PORTAINER_API_KEY },
baseURL: process.env.PORTAINER_URL, baseURL: process.env.PORTAINER_URL,
}); });
// In-Memory Store für Redeploy-Status // In-Memory Redeploy-Status
const redeployingStacks = {}; // { [stackId]: true/false } const redeployingStacks = {};
// HTTP Server + Socket.IO // HTTP Server + Socket.IO
const server = http.createServer(app); const server = http.createServer(app);
const io = new Server(server, { const io = new Server(server, { cors: { origin: "*" } });
cors: { origin: "*" } // ggf. auf Frontend-URL anpassen
});
// Socket.IO Verbindung
io.on("connection", (socket) => { io.on("connection", (socket) => {
console.log("Client verbunden:", socket.id); console.log("Client verbunden:", socket.id);
}); });
// Hilfsfunktion zum Broadcasten des Redeploy-Status
const broadcastRedeployStatus = (stackId, status) => { const broadcastRedeployStatus = (stackId, status) => {
redeployingStacks[stackId] = status; redeployingStacks[stackId] = status;
io.emit("redeployStatus", { stackId, status }); io.emit("redeployStatus", { stackId, status });
console.log(`Stack ${stackId} redeploying: ${status}`);
}; };
// Root-Endpoint // --- API Endpoints ---
app.get('/', (req, res) => {
console.log("Root Endpoint aufgerufen");
res.send('StackPulse Backend läuft. Nutze /api/stacks für die Daten.');
});
// Alle Stacks abrufen
app.get('/api/stacks', async (req, res) => { app.get('/api/stacks', async (req, res) => {
try { try {
const stacksRes = await axiosInstance.get('/api/stacks'); const stacksRes = await axiosInstance.get('/api/stacks');
const stacksWithStatus = await Promise.all( const stacksWithStatus = await Promise.all(
stacksRes.data.map(async (stack) => { stacksRes.data.map(async (stack) => {
try { try {
const statusRes = await axiosInstance.get(`/api/stacks/${stack.Id}/images_status?refresh=true`); const statusRes = await axiosInstance.get(
let statusEmoji = '✅'; // up-to-date `/api/stacks/${stack.Id}/images_status?refresh=true`
if (statusRes.data.Status === 'outdated') statusEmoji = '⚠️'; // outdated );
let statusEmoji = statusRes.data.Status === 'outdated' ? '⚠️' : '✅';
return { return { ...stack, updateStatus: statusEmoji, redeploying: redeployingStacks[stack.Id] || false };
...stack, } catch {
updateStatus: statusEmoji, return { ...stack, updateStatus: '❌', redeploying: redeployingStacks[stack.Id] || false };
redeploying: redeployingStacks[stack.Id] || false,
};
} catch (err) {
console.error(`Fehler beim Abrufen Remote Digest für Stack ${stack.Id}:`, err.message);
return {
...stack,
updateStatus: '❌', // Fehler
redeploying: redeployingStacks[stack.Id] || false,
};
} }
}) })
); );
stacksWithStatus.sort((a, b) => a.Name.localeCompare(b.Name)); stacksWithStatus.sort((a, b) => a.Name.localeCompare(b.Name));
res.json(stacksWithStatus); res.json(stacksWithStatus);
} catch (err) { } catch (err) {
console.error('Fehler beim Abrufen der Stacks:', err.message); res.status(500).json({ error: err.message });
if (err.response) res.status(err.response.status).json(err.response.data);
else res.status(500).json({ error: err.message });
} }
}); });
// Redeploy eines Stacks
app.put('/api/stacks/:id/redeploy', async (req, res) => { app.put('/api/stacks/:id/redeploy', async (req, res) => {
const { id } = req.params; const { id } = req.params;
try { try {
// Status auf "redeploying" setzen & an alle Clients senden
broadcastRedeployStatus(id, true); broadcastRedeployStatus(id, true);
const stackRes = await axiosInstance.get(`/api/stacks/${id}`); const stackRes = await axiosInstance.get(`/api/stacks/${id}`);
@@ -102,7 +90,6 @@ app.put('/api/stacks/:id/redeploy', async (req, res) => {
} else if (stack.Type === 2) { } else if (stack.Type === 2) {
const fileRes = await axiosInstance.get(`/api/stacks/${id}/file`); const fileRes = await axiosInstance.get(`/api/stacks/${id}/file`);
const stackFileContent = fileRes.data?.StackFileContent; const stackFileContent = fileRes.data?.StackFileContent;
if (!stackFileContent) throw new Error("Stack file konnte nicht geladen werden"); if (!stackFileContent) throw new Error("Stack file konnte nicht geladen werden");
const services = fileRes.data?.Config?.services || {}; const services = fileRes.data?.Config?.services || {};
@@ -113,28 +100,20 @@ app.put('/api/stacks/:id/redeploy', async (req, res) => {
await axiosInstance.post( await axiosInstance.post(
`/api/endpoints/${stack.EndpointId}/docker/images/create?fromImage=${encodeURIComponent(imageName)}` `/api/endpoints/${stack.EndpointId}/docker/images/create?fromImage=${encodeURIComponent(imageName)}`
); );
} catch (pullErr) { } catch {}
console.error(`Fehler beim Pull von ${imageName}:`, pullErr.message);
}
} }
await axiosInstance.put( await axiosInstance.put(`/api/stacks/${id}`,
`/api/stacks/${id}`,
{ StackFileContent: stackFileContent, Prune: false, PullImage: true }, { StackFileContent: stackFileContent, Prune: false, PullImage: true },
{ params: { endpointId: stack.EndpointId } } { params: { endpointId: stack.EndpointId } }
); );
} }
// Redeploy beendet, Status an alle Clients senden
broadcastRedeployStatus(id, false); broadcastRedeployStatus(id, false);
res.json({ success: true, message: 'Stack redeployed' }); res.json({ success: true, message: 'Stack redeployed' });
} catch (err) { } catch (err) {
// Fehler → Status zurücksetzen & an Clients senden
broadcastRedeployStatus(id, false); broadcastRedeployStatus(id, false);
console.error(`Fehler beim Redeploy von Stack ${id}:`, err.message); res.status(500).json({ error: err.message });
if (err.response) res.status(err.response.status).json(err.response.data);
else res.status(500).json({ error: err.message });
} }
}); });
+144
View File
@@ -0,0 +1,144 @@
import express from 'express';
import dotenv from 'dotenv';
import https from 'https';
import axios from 'axios';
import http from 'http';
import { Server } from 'socket.io';
dotenv.config();
const app = express();
app.use(express.json());
const PORT = 4001;
// HTTPS Agent für Self-Signed-Zertifikate
const agent = new https.Agent({ rejectUnauthorized: false });
// Axios-Instance für alle Portainer-Requests
const axiosInstance = axios.create({
httpsAgent: agent,
headers: { "X-API-Key": process.env.PORTAINER_API_KEY },
baseURL: process.env.PORTAINER_URL,
});
// In-Memory Store für Redeploy-Status
const redeployingStacks = {}; // { [stackId]: true/false }
// HTTP Server + Socket.IO
const server = http.createServer(app);
const io = new Server(server, {
cors: { origin: "*" } // ggf. auf Frontend-URL anpassen
});
// Socket.IO Verbindung
io.on("connection", (socket) => {
console.log("Client verbunden:", socket.id);
});
// Hilfsfunktion zum Broadcasten des Redeploy-Status
const broadcastRedeployStatus = (stackId, status) => {
redeployingStacks[stackId] = status;
io.emit("redeployStatus", { stackId, status });
console.log(`Stack ${stackId} redeploying: ${status}`);
};
// Root-Endpoint
app.get('/', (req, res) => {
console.log("Root Endpoint aufgerufen");
res.send('StackPulse Backend läuft. Nutze /api/stacks für die Daten.');
});
// Alle Stacks abrufen
app.get('/api/stacks', async (req, res) => {
try {
const stacksRes = await axiosInstance.get('/api/stacks');
const stacksWithStatus = await Promise.all(
stacksRes.data.map(async (stack) => {
try {
const statusRes = await axiosInstance.get(`/api/stacks/${stack.Id}/images_status?refresh=true`);
let statusEmoji = '✅'; // up-to-date
if (statusRes.data.Status === 'outdated') statusEmoji = '⚠️'; // outdated
return {
...stack,
updateStatus: statusEmoji,
redeploying: redeployingStacks[stack.Id] || false,
};
} catch (err) {
console.error(`Fehler beim Abrufen Remote Digest für Stack ${stack.Id}:`, err.message);
return {
...stack,
updateStatus: '❌', // Fehler
redeploying: redeployingStacks[stack.Id] || false,
};
}
})
);
stacksWithStatus.sort((a, b) => a.Name.localeCompare(b.Name));
res.json(stacksWithStatus);
} catch (err) {
console.error('Fehler beim Abrufen der Stacks:', err.message);
if (err.response) res.status(err.response.status).json(err.response.data);
else res.status(500).json({ error: err.message });
}
});
// Redeploy eines Stacks
app.put('/api/stacks/:id/redeploy', async (req, res) => {
const { id } = req.params;
try {
// Status auf "redeploying" setzen & an alle Clients senden
broadcastRedeployStatus(id, true);
const stackRes = await axiosInstance.get(`/api/stacks/${id}`);
const stack = stackRes.data;
if (stack.Type === 1) {
await axiosInstance.put(`/api/stacks/${id}/git/redeploy?endpointId=${stack.EndpointId}`);
} else if (stack.Type === 2) {
const fileRes = await axiosInstance.get(`/api/stacks/${id}/file`);
const stackFileContent = fileRes.data?.StackFileContent;
if (!stackFileContent) throw new Error("Stack file konnte nicht geladen werden");
const services = fileRes.data?.Config?.services || {};
for (const serviceName in services) {
const imageName = services[serviceName].image;
if (!imageName) continue;
try {
await axiosInstance.post(
`/api/endpoints/${stack.EndpointId}/docker/images/create?fromImage=${encodeURIComponent(imageName)}`
);
} catch (pullErr) {
console.error(`Fehler beim Pull von ${imageName}:`, pullErr.message);
}
}
await axiosInstance.put(
`/api/stacks/${id}`,
{ StackFileContent: stackFileContent, Prune: false, PullImage: true },
{ params: { endpointId: stack.EndpointId } }
);
}
// Redeploy beendet, Status an alle Clients senden
broadcastRedeployStatus(id, false);
res.json({ success: true, message: 'Stack redeployed' });
} catch (err) {
// Fehler → Status zurücksetzen & an Clients senden
broadcastRedeployStatus(id, false);
console.error(`Fehler beim Redeploy von Stack ${id}:`, err.message);
if (err.response) res.status(err.response.status).json(err.response.data);
else res.status(500).json({ error: err.message });
}
});
// Server starten
server.listen(PORT, '0.0.0.0', () => {
console.log(`Backend läuft auf Port ${PORT}`);
});
+4 -4
View File
@@ -5,9 +5,9 @@ services:
context: . context: .
dockerfile: Dockerfile dockerfile: Dockerfile
ports: ports:
- "4000:4000" - "4001:4001" # Host 5173 → Container 5173
environment: environment:
PORT: 4000 PORTAINER_URL: "https://10.10.10.21:9443/"
PORTAINER_URL: "https://your-portainer.example.com" PORTAINER_API_KEY: "ptr_ce3Wufxf+EKpqxc5ebcQjBkUMUoJmMpY3wGIvkgdxV0="
PORTAINER_API_KEY: "your_api_key_here" ENDPOINT_ID: "1"
restart: unless-stopped restart: unless-stopped
+13
View File
@@ -0,0 +1,13 @@
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile
ports:
- "4000:4000"
environment:
PORT: 4000
PORTAINER_URL: "https://your-portainer.example.com"
PORTAINER_API_KEY: "your_api_key_here"
restart: unless-stopped
+2 -6
View File
@@ -8,15 +8,11 @@ export default defineConfig({
port: 5173, port: 5173,
proxy: { proxy: {
"/api": { "/api": {
target: "http://127.0.0.1:4000", // dein Backend target: "http://localhost:4001", // dein Backend
changeOrigin: true, changeOrigin: true,
}, },
}, },
allowedHosts: [ allowedHosts: "all",
"10.10.10.23", // dein Dev-Rechner
"stackpulse.d-razz.de", // der Host, den du brauchst
"localhost",
],
}, },
}); });