WIP: Traefik?!

This commit is contained in:
Andras Bacsai 2022-05-12 13:02:14 +02:00
parent 60a428a952
commit 6bba37c36d
7 changed files with 216 additions and 2 deletions

View File

@ -0,0 +1,28 @@
version: '3.8'
services:
proxy:
image: traefik:v2.6
command:
- --api.insecure=true
- --entrypoints.web.address=:80
- --providers.docker=false
- --providers.docker.exposedbydefault=false
- --providers.http.endpoint=http://host.docker.internal:3000/traefik.json
- --providers.http.pollTimeout=5s
- --log.level=error
ports:
- '80:80'
- '443:443'
- '8080:8080'
volumes:
- /var/run/docker.sock:/var/run/docker.sock
extra_hosts:
- 'host.docker.internal:host-gateway'
networks:
- coolify-infra
networks:
coolify-infra:
attachable: true
name: coolify-infra

View File

@ -8,7 +8,7 @@
"dev:stop": "docker-compose -f docker-compose-dev.yaml down",
"dev:logs": "docker-compose -f docker-compose-dev.yaml logs -f --tail 10",
"studio": "npx prisma studio",
"start": "npx prisma migrate deploy && npx prisma generate && npx prisma db seed && node index.js",
"start": "npx prisma migrate deploy && npx prisma generate && npx prisma db seed && node build/index.js",
"build": "svelte-kit build",
"preview": "svelte-kit preview",
"check": "svelte-check --tsconfig ./tsconfig.json",

View File

@ -20,6 +20,7 @@ model Setting {
proxyHash String?
isAutoUpdateEnabled Boolean @default(false)
isDNSCheckEnabled Boolean @default(true)
disableHaproxy Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

View File

@ -6,11 +6,14 @@ export default async function (): Promise<void | {
body: { message: string; error: string };
}> {
try {
const settings = await prisma.setting.findFirst();
// Coolify Proxy
const localDocker = await prisma.destinationDocker.findFirst({
where: { engine: '/var/run/docker.sock' }
});
if (localDocker && localDocker.isCoolifyProxyUsed) {
console.log(settings.disableHaproxy);
if (localDocker && localDocker.isCoolifyProxyUsed && !settings.disableHaproxy) {
console.log('asd');
await startCoolifyProxy('/var/run/docker.sock');
}
// TCP Proxies

View File

@ -124,6 +124,13 @@
return errorNotification(error);
}
}
async function migrateToTraefik() {
try {
await post(`/update.json`, { type: 'migrateToTraefik' });
} catch ({ error }) {
return errorNotification(error);
}
}
</script>
<svelte:head>
@ -515,6 +522,13 @@
>Powered by <a href="https://coolify.io" target="_blank">Coolify</a></span
>
{/if}
<span class="fixed bottom-[20px] right-[10px] z-50 m-2 px-4 text-xs ">
<button on:click={migrateToTraefik}
>New proxy is available! <br />It is based on Traefik! Why?<br /><br />Haproxy uses a lots of
unnecessary memory. The update will cause a small interruption, but everything should go back
to normal in a few seconds!</button
>
</span>
{/if}
<main>
<slot />

152
src/routes/traefik.json.ts Normal file
View File

@ -0,0 +1,152 @@
import { asyncExecShell, getDomain, getEngine } from '$lib/common';
import * as db from '$lib/database';
import { checkContainer } from '$lib/haproxy';
export const get = async () => {
const applications = await db.prisma.application.findMany({
include: { destinationDocker: true, settings: true }
});
const data = {
applications: [],
services: [],
coolify: []
};
for (const application of applications) {
const {
fqdn,
id,
port,
destinationDocker,
destinationDockerId,
settings: { previews },
updatedAt
} = application;
if (destinationDockerId) {
const { engine, network } = destinationDocker;
const isRunning = await checkContainer(engine, id);
if (fqdn) {
const domain = getDomain(fqdn);
const isHttps = fqdn.startsWith('https://');
const isWWW = fqdn.includes('www.');
const redirectValue = `${isHttps ? 'https://' : 'http://'}${domain}%[capture.req.uri]`;
if (isRunning) {
data.applications.push({
id,
port: port || 3000,
domain,
isRunning,
isHttps,
redirectValue,
redirectTo: isWWW ? domain.replace('www.', '') : 'www.' + domain,
updatedAt: updatedAt.getTime()
});
}
if (previews) {
const host = getEngine(engine);
const { stdout } = await asyncExecShell(
`DOCKER_HOST=${host} docker container ls --filter="status=running" --filter="network=${network}" --filter="name=${id}-" --format="{{json .Names}}"`
);
const containers = stdout
.trim()
.split('\n')
.filter((a) => a)
.map((c) => c.replace(/"/g, ''));
if (containers.length > 0) {
for (const container of containers) {
const previewDomain = `${container.split('-')[1]}.${domain}`;
data.applications.push({
id: container,
port: port || 3000,
domain: previewDomain,
isRunning,
isHttps,
redirectValue,
redirectTo: isWWW ? previewDomain.replace('www.', '') : 'www.' + previewDomain,
updatedAt: updatedAt.getTime()
});
}
}
}
}
}
}
const traefik = {
http: {
routers: {},
services: {}
}
};
for (const application of data.applications) {
const { id, port, domain, isHttps, redirectValue, redirectTo, updatedAt } = application;
traefik.http.routers[id] = {
entrypoints: ['web'],
rule: `Host(\`${domain}\`)`,
service: id
};
traefik.http.services[id] = {
loadbalancer: {
servers: [
{
url: `http://${id}:${port}`
}
]
}
};
}
return {
status: 200,
body: {
...traefik
// "http": {
// "routers": {
// "coolify": {
// "entrypoints": [
// "web"
// ],
// "middlewares": [
// "coolify-hc"
// ],
// "rule": "Host(`staging.coolify.io`)",
// "service": "coolify"
// },
// "static.example.coolify.io": {
// "entrypoints": [
// "web"
// ],
// "rule": "Host(`static.example.coolify.io`)",
// "service": "static.example.coolify.io"
// }
// },
// "services": {
// "coolify": {
// "loadbalancer": {
// "servers": [
// {
// "url": "http://coolify:3000"
// }
// ]
// }
// },
// "static.example.coolify.io": {
// "loadbalancer": {
// "servers": [
// {
// "url": "http://cl32p06f58068518cs3thg6vbc7:80"
// }
// ]
// }
// }
// },
// "middlewares": {
// "coolify-hc": {
// "replacepathregex": {
// "regex": "/dead.json",
// "replacement": "/undead.json"
// }
// }
// }
// }
}
};
};

View File

@ -61,6 +61,22 @@ export const post: RequestHandler = async (event) => {
} catch (error) {
return ErrorHandler(error);
}
} else if (type === 'migrateToTraefik') {
try {
const settings = await db.prisma.setting.findFirst({});
await db.prisma.setting.update({
where: { id: settings.id },
data: { disableHaproxy: true }
});
await asyncExecShell(`docker stop -t 0 coolify-haproxy`);
await asyncExecShell(`docker rm coolify-haproxy`);
return {
status: 200,
body: {}
};
} catch (error) {
return ErrorHandler(error);
}
}
return {
status: 500