From 107bb05d471118e3f691a6a0565e5935e4a4e7b0 Mon Sep 17 00:00:00 2001
From: Imbus <imbus64@protonmail.com>
Date: Wed, 18 Oct 2023 03:47:29 +0200
Subject: [PATCH] Working multi-stage container build

---
 client/.containerignore |  2 ++
 justfile                |  7 ++++---
 server/Containerfile    | 29 ++++++++++++++++++++++++-----
 3 files changed, 30 insertions(+), 8 deletions(-)
 create mode 100644 client/.containerignore

diff --git a/client/.containerignore b/client/.containerignore
new file mode 100644
index 0000000..de4d1f0
--- /dev/null
+++ b/client/.containerignore
@@ -0,0 +1,2 @@
+dist
+node_modules
diff --git a/justfile b/justfile
index a7ddfc0..a16ef15 100644
--- a/justfile
+++ b/justfile
@@ -7,14 +7,15 @@ build-client:
 
 # npm run build places the build in the server/public directory
 build-container: build-client
-    cd server && podman build -t server .
+    cd server && podman build -t fb-server .
 
 start-release: build-container
-    podman run -d -p 8080:8080 --name frostbyte server
+    podman container rm -f frostbyte
+    podman run -d -p 8080:8080 --name frostbyte fb-server
 
 clean: 
     podman container rm -f frostbyte
-    podman image rm -f server
+    podman image rm -f fb-server
     rm -rf client/dist
     rm -rf client/node_modules
     rm -rf server/public
diff --git a/server/Containerfile b/server/Containerfile
index fb6ade3..fa91c2b 100644
--- a/server/Containerfile
+++ b/server/Containerfile
@@ -1,7 +1,26 @@
+# The rust:latest-alpine uses musl libc
 FROM docker.io/rust:latest as builder
-workdir /app
-ADD . /app
-RUN cargo clean
-RUN cargo build --release
+WORKDIR /build
+ADD . /build
+RUN apt update
+RUN apt install musl musl-dev musl-tools -y
+RUN rustup target add x86_64-unknown-linux-musl
+RUN cargo build --target x86_64-unknown-linux-musl --release
+
+FROM docker.io/alpine:latest as runner
+
+# Add a non-root user for running the server
+RUN addgroup -S user && adduser -S user -G user
+
+# Copy the server binary and the public directory
+WORKDIR /runner
+COPY --from=builder /build/target/x86_64-unknown-linux-musl/release/server /runner/server
+COPY --from=builder /build/public /runner/public
+
+# Make sure the user can access the files
+RUN chown -R user:user /runner
+USER user
+
+# Run the server
 EXPOSE 8080
-CMD ["cargo", "run", "--release"]
\ No newline at end of file
+CMD ["./server"]