Build a rock for a Django application¶
In this tutorial, we’ll create a simple Django application and learn how to
containerise it in a rock, using Rockcraft’s django-framework
extension.
Setup¶
We recommend starting from a clean Ubuntu 22.04 installation. If you don’t have one available, you can create one using Multipass:
Is Multipass already installed and active? Check by running
snap services multipass
If you see the multipass
service but it isn’t “active”, then you’ll
need to run sudo snap start multipass
. On the other hand, if you get
an error saying snap "multipass" not found
, then you must install
Multipass:
sudo snap install multipass
See Multipass installation instructions, switch to Windows in the drop down.
See Multipass installation instructions, switch to macOS in the drop down.
Then you can create the VM with the following command:
multipass launch --disk 10G --name rock-dev 22.04
Finally, once the VM is up, open a shell into it:
multipass shell rock-dev
LXD will be required for building the rock. Make sure it is installed and initialised:
sudo snap install lxd
lxd init --auto
In order to create the rock, you’ll need to install Rockcraft:
sudo snap install rockcraft --classic
We’ll use Docker to run the rock. You can install it as a snap
:
sudo snap install docker
Warning
There is a known connectivity issue with LXD and Docker. If you see a networking issue such as “A network related operation failed in a context of no network access”, make sure you apply one of the fixes suggested here.
Note that you’ll also need a text editor. You can either install one of your
choice or simply use one of the already existing editors in your Ubuntu
environment (like vi
).
Finally, create a new directory for this tutorial and go inside it:
mkdir django-hello-world
cd django-hello-world
Create the Django application¶
Start by creating the “Hello, world” Django application that will be used for this tutorial.
Create a requirements.txt
file, copy the following text into it and then
save it:
Django
In order to test the Django application locally (before packing it into a rock),
install python3-venv
and create a virtual environment:
sudo apt-get update && sudo apt-get install python3-venv -y
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
Create a new project using django-admin
:
django-admin startproject django_hello_world
Change into the django_hello_world
directory and run the Django application
using python manage.py runserver
to verify that it works.
Test the Django application by using curl
to send a request to the root
endpoint. You may need a new terminal for this, if you are using Multipass use
multipass shell rock-dev
to get another terminal:
curl localhost:8000
The Django application should respond with
The install worked successfully! Congratulations!
.
Note
The response from the Django application includes HTML and CSS which makes
it difficult to read on a terminal. Visit http://localhost:8000
using a
browser to see the fully rendered page.
The Django application looks good, so let’s stop it for now by pressing Ctrl + C.
Pack the Django application into a rock¶
First, we’ll need a rockcraft.yaml
file. Rockcraft will automate its
creation and tailoring for a Django application by using the
django-framework
profile:
cd ..
rockcraft init --profile django-framework
The rockcraft.yaml
file will automatically be created in your working
directory. Open it in a text editor and check that the name
is
django-hello-world
. Ensure that platforms
includes the architecture of
your host. For example, if your host uses the ARM architecture, include
arm64
in platforms
.
Note
For this tutorial, we’ll use the name
django-hello-world
and assume
you are running on an amd64
platform. Check the architecture of your
system using dpkg --print-architecture
.
The name
, version
and platform
all influence the name of the
generated .rock
file.
Pack the rock:
rockcraft pack
Note
Depending on your network, this step can take a couple of minutes to finish.
Once Rockcraft has finished packing the Django rock, you’ll find a new file in
your working directory (an OCI archive) with the .rock
extension:
ls *.rock -l --block-size=MB
The created rock is about 75MB in size. We will reduce its size later in this tutorial.
Note
If you changed the name
or version
in rockcraft.yaml
or are not
on an amd64
platform, the name of the .rock
file will be different
for you.
The size of your rock may vary depending on factors like the architecture you are building on and the packages installed at the time of packing.
Run the Django rock with Docker¶
We already have the rock as an OCI archive. Now we’ll need to load it into Docker:
sudo rockcraft.skopeo --insecure-policy \
copy oci-archive:django-hello-world_0.1_amd64.rock \
docker-daemon:django-hello-world:0.1
Check that the image was successfully loaded into Docker:
sudo docker images django-hello-world:0.1
The output should list your Django container image, along with its tag, ID and size:
REPOSITORY TAG IMAGE ID CREATED SIZE
django-hello-world 0.1 5cd019b51db9 6 days ago 184MB
Note
The size of the image reported by Docker is the uncompressed size which is
larger than the size of the compressed .rock
file.
Now we’re ready to run the rock and test your containerised Django application:
sudo docker run --rm -d -p 8000:8000 \
--name django-hello-world django-hello-world:0.1
Use the same curl
command as before to send a request to the Django
application’s root endpoint which is running inside the container:
curl localhost:8000
The Django application should again respond with
The install worked successfully! Congratulations!
.
View the application logs¶
When deploying your Django rock, you can always get the application logs via
pebble
:
sudo docker exec django-hello-world pebble logs django
As a result, Pebble will give you the logs for the
django
service running inside the container.
You should expect to see something similar to this:
2024-08-20T06:34:36.114Z [django] [2024-08-20 06:34:36 +0000] [17] [INFO] Starting gunicorn 23.0.0
2024-08-20T06:34:36.115Z [django] [2024-08-20 06:34:36 +0000] [17] [INFO] Listening at: http://0.0.0.0:8000 (17)
2024-08-20T06:34:36.115Z [django] [2024-08-20 06:34:36 +0000] [17] [INFO] Using worker: sync
2024-08-20T06:34:36.116Z [django] [2024-08-20 06:34:36 +0000] [18] [INFO] Booting worker with pid: 18
You can also choose to follow the logs by using the -f
option with the
pebble logs
command above. To stop following the logs, press Ctrl +
C.
Cleanup¶
Now we have a fully functional rock for our Django application! This concludes the first part of this tutorial, so we can stop the container and remove the respective image for now:
sudo docker stop django-hello-world
sudo docker rmi django-hello-world:0.1
Chisel the rock¶
This is an optional but recommended step, especially if you’re looking to deploy your rock into a production environment. With Chisel you can produce lean and production-ready rocks by getting rid of all the contents that are not needed for your Django application to run. This results in a much smaller rock with a reduced attack surface.
Note
It is recommended to run chiselled images in production. For development, you may prefer non-chiselled images as they will include additional development tooling (such as for debugging).
The first step towards chiselling your rock is to ensure you are using a
bare
base.
In rockcraft.yaml
, change the base
to bare
and add
build-base: ubuntu@22.04
:
sed -i \
"s/base: .*/base: bare\nbuild-base: [email protected]/g" \
rockcraft.yaml
So that we can compare the size after chiselling, open the rockcraft.yaml
file and change the version
(e.g. to 0.1-chiselled
). Pack the rock with
the new bare
base:
rockcraft pack
As before, verify that the new rock was created:
ls *.rock -l --block-size=MB
You’ll verify that the new Django rock is now approximately 15% smaller
in size! And that’s just because of the simple change of base
.
And the functionality is still the same. As before, we can confirm this by running the rock with Docker:
sudo rockcraft.skopeo --insecure-policy \
copy oci-archive:django-hello-world_0.1-chiselled_amd64.rock \
docker-daemon:django-hello-world:0.1-chiselled
sudo docker images django-hello-world:0.1-chiselled
sudo docker run --rm -d -p 8000:8000 \
--name django-hello-world django-hello-world:0.1-chiselled
and then using the same curl
request:
curl localhost:8000
Unsurprisingly, the Django application should still respond with
The install worked successfully! Congratulations!
.
Cleanup¶
And that’s it. We can now stop the container and remove the corresponding image:
sudo docker stop django-hello-world
sudo docker rmi django-hello-world:0.1-chiselled
Update the Django application¶
As a final step, let’s update our application. For example,
we want to add a new /time/
endpoint which returns the current time.
cd django_hello_world
django-admin startapp time_app
Open the file time_app/views.py
and replace its contents with the following:
import datetime
from django.http import HttpResponse
def index(request):
return HttpResponse(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
Create the file time_app/urls.py
with the following contents:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
Open the file django_hello_world/urls.py
and replace its contents with
the following:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("time/", include("time_app.urls")),
path("admin/", admin.site.urls),
]
Since we are creating a new version of the application, go back to the
tutorial root directory using cd ..
and open the rockcraft.yaml
file and
change the version
(e.g. to 0.2
).
Note
rockcraft pack
will create a new image with the updated code even if you
don’t change the version. It is recommended to change the version whenever
you make changes to the application in the image.
Pack and run the rock using similar commands as before:
rockcraft pack
sudo rockcraft.skopeo --insecure-policy copy \
oci-archive:django-hello-world_0.2_amd64.rock \
docker-daemon:django-hello-world:0.2
sudo docker images django-hello-world:0.2
sudo docker run --rm -d -p 8000:8000 \
--name django-hello-world django-hello-world:0.2
Note
Note that the resulting .rock
file will now be named differently, as
its new version will be part of the filename.
Finally, use curl
to send a request to the /time/
endpoint:
curl localhost:8000/time/
The updated application should respond with the current date and time (e.g.
2024-08-20 07:28:19
).
Note
If you are getting a 404
for the /time/
endpoint, check the
Troubleshooting steps below.
Cleanup¶
We can now stop the container and remove the corresponding image:
sudo docker stop django-hello-world
sudo docker rmi django-hello-world:0.2
Reset your environment¶
We’ve reached the end of this tutorial.
If you’d like to reset your working environment, you can simply run the following:
# exit and delete the virtual environment
deactivate
rm -rf .venv django_hello_world __pycache__
# delete all the files created during the tutorial
rm django-hello-world_0.1_amd64.rock \
django-hello-world_0.1-chiselled_amd64.rock \
django-hello-world_0.2_amd64.rock \
rockcraft.yaml requirements.txt
If using Multipass...
If you created an instance using Multipass, you can also clean it up. Start by exiting it:
exit
And then you can proceed with its deletion:
multipass delete rock-dev
multipass purge
Troubleshooting¶
Application updates not taking effect?
Upon changing your Django application and re-packing the rock, if you believe
your changes are not taking effect (e.g. the /time/
endpoint is returning a
404), try running rockcraft clean
and pack the rock again with
rockcraft pack
.