13 ci cd Implementation - Jeremy-Feytens/IT-Landscape GitHub Wiki
Automate the building and publishing of a Docker image for my PyTorch application to the GitHub Container Registry (GHCR) every time there is a change pushed to the main
branch.
- My PyTorch script
app.py
andrequirements.txt
are stored in the GitHub repository.
import torch
import torch.nn as nn
import torch.optim as optim
torch.manual_seed(0)
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
y = 2 * x + 1 + 0.1 * torch.randn_like(x)
model = nn.Sequential(
nn.Linear(in_features=1, out_features=1)
)
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.1)
num_epochs = 50
for epoch in range(1, num_epochs + 1):
preds = model(x)
loss = criterion(preds, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if epoch % 10 == 0 or epoch == 1:
w, b = model[0].weight.item(), model[0].bias.item()
print(f"Epoch {epoch:2d}: loss={loss.item():.4f}, weight={w:.3f}, bias={b:.3f}")
test_x = torch.tensor([[4.0]])
pred_y = model(test_x)
print(f"\nModel prediction: for x=4.0 → y≈{pred_y.item():.3f} (true y=9.0)")
- A
Dockerfile
was added to build a container image with Python and all required dependencies.
FROM python:3.13-alpine
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
EXPOSE 5000
CMD ["python", "app.py"]
- Created a workflow file at
.github/workflows/docker-build.yml
. - This workflow is triggered automatically on every push to the
main
branch.
Step | Description |
---|---|
Checkout repository | Uses actions/checkout@v4 to fetch the latest code. |
Log in to GHCR | Logs in to GitHub Container Registry using a Personal Access Token stored as secret CR_PAT . |
Set variables | Converts repository owner name to lowercase and defines the Docker image name for consistent tagging. |
Build Docker image | Builds the Docker image tagged as ghcr.io/<owner>/my-pytorch-app:<commit-sha> . |
Push Docker image | Pushes the Docker image to the GitHub Container Registry. |
Save image tarball | Saves the built image locally as image.tar . |
Upload artifact | Uploads image.tar as a workflow artifact for easy downloading. |
- On each push to
main
, the workflow is triggered. - A new Docker image is built and published to GHCR.
- The image is available at
ghcr.io/<repo-owner>/my-pytorch-app:<commit-sha>
. - The workflow completes successfully and can be viewed in the GitHub Actions tab.
By implementing this CI/CD pipeline, the process of building and publishing my application is fully automated. This enables rapid deployment of new versions without manual intervention, saving time and reducing the risk of errors.