
Swift Example in Docker
π Run a Swift Application in Docker
You can run Swift inside a Docker container for development or production. Hereβs how to do it step by step.
π Step 1: Install Docker (If Not Installed)
If you haven't installed Docker yet, follow this guide for Ubuntu or run:
sudo apt update && sudo apt install -y docker.iosudo systemctl start dockersudo systemctl enable docker
π Step 2: Create a Simple Swift App
Create a new project folder:
mkdir swift-docker && cd swift-docker
Create a new Swift file:
echo 'print("Hello from Swift in Docker!")' > main.swift
π³ Step 3: Create a Dockerfile
Inside your swift-docker
folder, create a file named Dockerfile
:
# Use the official Swift imageFROM swift:latest # Set the working directoryWORKDIR /app# Copy the Swift source file into the containerCOPY main.swift .# Compile the Swift fileRUN swiftc main.swift -o main# Run the compiled Swift binaryCMD ["./main"]
π Step 4: Build the Docker Image
Run this command in the swift-docker
folder:
docker build -t swift-app .
π Step 5: Run the Swift Container
After building, run the container:
docker run --rm swift-app
β Expected Output:
Hello from Swift in Docker!
πΉ (Optional) Run Swift REPL in Docker
If you want to run an interactive Swift shell, use:
docker run -it --rm swift swift
This lets you write and execute Swift commands interactively.
π― Summary
β
Created a simple Swift app
β
Wrote a Dockerfile
β
Built & ran the app inside Docker
β
(Optional) Opened Swift REPL inside Docker
Now you have Swift running in a Docker container! π
Would you like help with Swift server-side (Vapor) in Docker? π