sudo apt-get update
sudo apt-get install ca-certificates curl gnupg
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg
Add the repositiories apt source:
echo \
"deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
"$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
Install the packages:
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
Run the hello world
image to verify docker is installed:
sudo docker run hello-world
Or you can use the script:
curl -fsSL https://get.docker.com -o get-docker.sh
#sudo sh ./get-docker.sh --dry-run #See what it will do
sudo sh ./get-docker.sh
IF you do not want to use sudo
to run docker you can add your user to a group called docker
but keep in mind any user in that group wil have root privileges:
-
Create
docker
group$ sudo groupadd docker
-
Add your user to
docker
group$ sudo usermod -aG docker $USER
-
Log out and log back in
If in a virtual machine, restart the virtual machine
Can also run the following command to activate the changes to groups:
$ newgrp docker
Run the hello world
image without sudo
:
docker run hello-world
For Debian / Ubuntu this is done by default for other distibutions:
sudo systemctl enable docker.service
sudo systemctl enable containerd.service
Using the basic Django Rest Framework CRUD REST API as a code base we can make a docker image, boilerplate code for the API can be found here
In the root folder of the project create a file called Dockerfile
# Use the official Python image as the base image
FROM python:3.8
# Set environment variables
ENV PYTHONUNBUFFERED 1
ENV DJANGO_SETTINGS_MODULE=ToDo.settings
ENV ALLOWED_HOSTS='0.0.0.0,localhost'
# Set the working directory in the container
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app/
# Install gunicorn
RUN pip3 install gunicorn
# Install dependencies
RUN pip3 install --no-cache-dir -r requirements.txt
# Modify the ALLOWED_HOSTS directly in settings.py
RUN sed -i 's/ALLOWED_HOSTS = \[\]/ALLOWED_HOSTS = ["0.0.0.0"]/g' ToDo/settings.py
# Collect static files
RUN python3 manage.py collectstatic --noinput
# Expose the port the application runs on
EXPOSE 8000
# Run the Django application with Gunicorn
CMD ["gunicorn", "ToDo.wsgi:application", "--bind", ":8000"]
To build the Docker image use the below command:
docker build -t todo_django_api .
To run the container use the below command:
docker run -p 8000:8000 todo_django_api`
logs
docker logs
docker service logs
#docker todo_django_api logs