Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

feat: revert to remote image

Andras Bacsai1a28e65e5001
diff --git a/apps/api/src/jobs/deployApplication.ts b/apps/api/src/jobs/deployApplication.ts
index 48e3a31739..5fa01cd45a 100644
--- a/apps/api/src/jobs/deployApplication.ts
+++ b/apps/api/src/jobs/deployApplication.ts
@@ -214,7 +214,6 @@ import * as buildpacks from '../lib/buildPacks';
return;
}
-
const originalApplicationId = application.id
const {
id: applicationId,
@@ -259,7 +258,16 @@ import * as buildpacks from '../lib/buildPacks';
let imageId = applicationId;
let domain = getDomain(fqdn);
- let tag = null
+
+ let location = null;
+
+ let tag = null;
+ let customTag = null;
+ let imageName = null;
+
+ let imageFoundLocally = false;
+ let imageFoundRemotely = false;
+
if (pullmergeRequestId) {
const previewApplications = await prisma.previewApplication.findMany({ where: { applicationId: originalApplicationId, pullmergeRequestId } })
if (previewApplications.length > 0) {
@@ -363,6 +371,12 @@ import * as buildpacks from '../lib/buildPacks';
tag = `${commit.slice(0, 7)}-${pullmergeRequestId}`;
}
+ customTag = application.dockerRegistryImageName.split(':')[1] || tag;
+ if (pullmergeRequestId) {
+ customTag = `${customTag}-${pullmergeRequestId}`;
+ }
+ imageName = application.dockerRegistryImageName.split(':')[0];
+
try {
await prisma.build.update({ where: { id: buildId }, data: { commit } });
} catch (err) { }
@@ -380,16 +394,32 @@ import * as buildpacks from '../lib/buildPacks';
deployNeeded = true;
}
- let imageFound = false;
try {
await executeDockerCmd({
dockerId: destinationDocker.id,
command: `docker image inspect ${applicationId}:${tag}`
})
- imageFound = true;
+ imageFoundLocally = true;
} catch (error) {
//
}
+
+ const { url, username, password } = dockerRegistry
+ location = await saveDockerRegistryCredentials({ url, username, password, workdir })
+
+ try {
+ await executeDockerCmd({
+ dockerId: destinationDocker.id,
+ command: `docker ${location ? `--config ${location}` : ''} pull ${imageName}:${customTag}`
+ })
+ imageFoundRemotely = true;
+ } catch (error) {
+ //
+ }
+ let imageFound = `${applicationId}:${tag}`
+ if (imageFoundRemotely) {
+ imageFound = `${imageName}:${customTag}`
+ }
await copyBaseConfigurationFiles(buildPack, workdir, buildId, applicationId, baseImage);
const labels = makeLabelForStandaloneApplication({
applicationId,
@@ -410,7 +440,7 @@ import * as buildpacks from '../lib/buildPacks';
publishDirectory
});
if (forceRebuild) deployNeeded = true
- if (!imageFound || deployNeeded) {
+ if ((!imageFoundLocally && !imageFoundRemotely) || deployNeeded) {
if (buildpacks[buildPack])
await buildpacks[buildPack]({
dockerId: destinationDocker.id,
@@ -456,7 +486,15 @@ import * as buildpacks from '../lib/buildPacks';
throw new Error(`Build pack ${buildPack} not found.`);
}
} else {
- await saveBuildLog({ line: 'Build image already available - no rebuild required.', buildId, applicationId });
+ if (imageFoundRemotely) {
+ await saveBuildLog({ line: `Container image ${imageFound} found in Docker Registry - reuising it`, buildId, applicationId });
+ } else {
+ if (imageFoundLocally) {
+ await saveBuildLog({ line: `Container image ${imageFound} found locally - reuising it`, buildId, applicationId });
+ }
+ }
+
+
}
if (buildPack === 'compose') {
@@ -550,7 +588,7 @@ import * as buildpacks from '../lib/buildPacks';
version: '3.8',
services: {
[imageId]: {
- image: `${applicationId}:${tag}`,
+ image: imageFound,
container_name: imageId,
volumes,
env_file: envFound ? [`${workdir}/.env`] : [],
@@ -610,9 +648,7 @@ import * as buildpacks from '../lib/buildPacks';
return;
}
try {
- if (application.dockerRegistryImageName) {
- const customTag = application.dockerRegistryImageName.split(':')[1] || tag;
- const imageName = application.dockerRegistryImageName.split(':')[0];
+ if (application.dockerRegistryImageName && (!imageFoundRemotely || forceRebuild)) {
await saveBuildLog({ line: `Pushing ${imageName}:${customTag} to Docker Registry... It could take a while...`, buildId, applicationId: application.id });
await pushToRegistry(application, workdir, tag, imageName, customTag)
await saveBuildLog({ line: "Success 🎉", buildId, applicationId: application.id });
diff --git a/apps/api/src/routes/api/v1/applications/handlers.ts b/apps/api/src/routes/api/v1/applications/handlers.ts
index bcebb21d89..f44b53bc3e 100644
--- a/apps/api/src/routes/api/v1/applications/handlers.ts
+++ b/apps/api/src/routes/api/v1/applications/handlers.ts
@@ -7,7 +7,7 @@ import yaml from 'js-yaml';
import csv from 'csvtojson';
import { day } from '../../../../lib/dayjs';
-import { setDefaultBaseImage, setDefaultConfiguration } from '../../../../lib/buildPacks/common';
+import { saveDockerRegistryCredentials, setDefaultBaseImage, setDefaultConfiguration } from '../../../../lib/buildPacks/common';
import { checkDomainsIsValidInDNS, checkExposedPort, createDirectories, decrypt, defaultComposeConfiguration, encrypt, errorHandler, executeDockerCmd, generateSshKeyPair, getContainerUsage, getDomain, isDev, isDomainConfigured, listSettings, prisma, stopBuild, uniqueName } from '../../../../lib/common';
import { checkContainer, formatLabelsOnDocker, removeContainer } from '../../../../lib/docker';
@@ -458,8 +458,8 @@ export async function restartApplication(request: FastifyRequest<RestartApplicat
if (application?.destinationDockerId) {
const buildId = cuid();
const { id: dockerId, network } = application.destinationDocker;
- const { secrets, pullmergeRequestId, port, repository, persistentStorage, id: applicationId, buildPack, exposePort } = application;
-
+ const { dockerRegistry, secrets, pullmergeRequestId, port, repository, persistentStorage, id: applicationId, buildPack, exposePort } = application;
+ let location = null;
const envs = [
`PORT=${port}`
];
@@ -480,7 +480,9 @@ export async function restartApplication(request: FastifyRequest<RestartApplicat
});
}
const { workdir } = await createDirectories({ repository, buildId });
- const labels = []
+ const labels = [
+ `coolify.managed=true`,
+ ]
let image = null
if (imageId) {
image = imageId
@@ -497,18 +499,30 @@ export async function restartApplication(request: FastifyRequest<RestartApplicat
})
}
}
-
- let imageFound = false;
+ const { url, username, password } = dockerRegistry
+ location = await saveDockerRegistryCredentials({ url, username, password, workdir })
+ let imageFoundLocally = false;
try {
await executeDockerCmd({
dockerId,
command: `docker image inspect ${image}`
})
- imageFound = true;
+ imageFoundLocally = true;
} catch (error) {
//
}
- if (!imageFound) {
+ let imageFoundRemotely = false;
+ try {
+ await executeDockerCmd({
+ dockerId,
+ command: `docker ${location ? `--config ${location}` : ''} pull ${image}`
+ })
+ imageFoundRemotely = true;
+ } catch (error) {
+ //
+ }
+
+ if (!imageFoundLocally && !imageFoundRemotely) {
throw { status: 500, message: 'Image not found, cannot restart application.' }
}
await fs.writeFile(`${workdir}/.env`, envs.join('\n'));
@@ -554,8 +568,13 @@ export async function restartApplication(request: FastifyRequest<RestartApplicat
volumes: Object.assign({}, ...composeVolumes)
};
await fs.writeFile(`${workdir}/docker-compose.yml`, yaml.dump(composeFile));
- await executeDockerCmd({ dockerId, command: `docker stop -t 0 ${id}` })
- await executeDockerCmd({ dockerId, command: `docker rm ${id}` })
+ try {
+ await executeDockerCmd({ dockerId, command: `docker stop -t 0 ${id}` })
+ await executeDockerCmd({ dockerId, command: `docker rm ${id}` })
+ } catch (error) {
+ //
+ }
+
await executeDockerCmd({ dockerId, command: `docker compose --project-directory ${workdir} up -d` })
return reply.code(201).send();
}
diff --git a/apps/ui/src/routes/applications/[id]/revert.svelte b/apps/ui/src/routes/applications/[id]/revert.svelte
index de891d561f..5bf94c480d 100644
--- a/apps/ui/src/routes/applications/[id]/revert.svelte
+++ b/apps/ui/src/routes/applications/[id]/revert.svelte
@@ -26,10 +26,12 @@
import { get, post } from '$lib/api';
import { status, addToast } from '$lib/store';
import { errorNotification } from '$lib/common';
+ import Explainer from '$lib/components/Explainer.svelte';
const { id } = $page.params;
+ let remoteImage: any = null;
- async function revertApplication(image: any) {
+ async function revertToLocal(image: any) {
const sure = confirm(`Are you sure you want to revert to ${image.tag} ?`);
if (sure) {
try {
@@ -49,25 +51,46 @@
}
}
}
+ async function revertToRemote() {
+ const sure = confirm(`Are you sure you want to revert to ${remoteImage} ?`);
+ if (sure) {
+ try {
+ $status.application.initialLoading = true;
+ $status.application.loading = true;
+ await post(`/applications/${id}/restart`, { imageId: remoteImage });
+ addToast({
+ type: 'success',
+ message: 'Revert successful.'
+ });
+ } catch (error) {
+ return errorNotification(error);
+ } finally {
+ $status.application.initialLoading = false;
+ $status.application.loading = false;
+ }
+ }
+ }
</script>
<div class="w-full">
<div class="mx-auto w-full">
<div class="flex flex-row border-b border-coolgray-500 mb-6 space-x-2">
- <div class="title font-bold pb-3">Revert</div>
- </div>
- <div>
- You can revert application to a previously built image. Currently only locally stored images
- supported.
+ <div class="title font-bold pb-3">
+ Revert <Explainer
+ position="dropdown-bottom"
+ explanation="You can revert application to a previously built image. Currently only locally stored images
+ supported."
+ />
+ </div>
</div>
- <br />
- <div class="pb-4">
+ <div class="pb-4 text-xs">
If you do not want the next commit to overwrite the reverted application, temporary disable <span
class="text-yellow-400 font-bold">Automatic Deployment</span
>
feature <a href={`/applications/${id}/features`}>here</a>.
</div>
{#if imagesAvailables.length > 0}
+ <div class="text-xl font-bold pb-3">Local Images</div>
<div
class="px-4 lg:pb-10 pb-6 flex flex-wrap items-center justify-center lg:justify-start gap-8"
>
@@ -104,7 +127,7 @@
{#if image.repository + ':' + image.tag !== runningImage}
<button
class="btn btn-sm btn-primary w-full"
- on:click={() => revertApplication(image)}>Revert Now</button
+ on:click={() => revertToLocal(image)}>Revert Now</button
>
{:else}
<button
@@ -118,9 +141,25 @@
{/each}
</div>
{:else}
- <div class="flex flex-col justify-center items-center">
- <div class="text-xl font-bold">No images available</div>
+ <div class="flex flex-col pb-10">
+ <div class="text-xl font-bold">No Local images available</div>
</div>
{/if}
+ <div class="text-xl font-bold pb-3">
+ Remote Images (Docker Registry) <Explainer
+ position="dropdown-bottom"
+ explanation="If the image is not available or you are unauthorized to access it, you will not be able to revert to it."
+ />
+ </div>
+ <form on:submit|preventDefault={revertToRemote}>
+ <input
+ id="dockerImage"
+ name="dockerImage"
+ required
+ placeholder="coollabsio/coolify:0.0.1"
+ bind:value={remoteImage}
+ />
+ <button class="btn btn-sm btn-primary" type="submit">Revert Now</button>
+ </form>
</div>
</div>