Django Tips #5: Docker
Docker is a very popular tool for managing Django projects. Many professional developers use it but I find it is still confusing to many newcomers. In this post I’ll attempt to demystify what Docker is and why it is such a powerful addition to working with Django.
What is Docker?
The easiest way to think of Docker is as a large virtual environment that contains everything needed for our Django project: dependencies, databases, caching services, and any other tools needed.
This is not the same thing as a virtual environment. A virtual environment helps isolate individual software packages–like which version of Django you’re using and other Python packages–but it cannot extend to outside services like a PostgreSQL database. Docker can. It is an entire contained development environment that can be used both locally and in production.
Django ships with SQLite as the default database and it is a great choice for quick prototyping. But…you don’t want to deploy to SQLite in production, instead you’re more likely to use something like PostgreSQL or MySQL. While you can use SQLite locally and then deploy to a production database this is not advised. There are many bugs that can creep up when your local dev environment does not match your production environment.
The answer is to run your own instance of, say, PostgreSQL locally. However this can be a challenging experience. You must correctly install and then run a PostgreSQL instance on its own. Then you need to connect your Django app. It’s doable, but error-prone.
And if you have additional services running in production like a Redis cache that also is tough to configure locally but much simpler with Docker. You can accurately mimic your production environment locally, which is the holy grail for web developers.
Now consider what happens if you’re on a team of developers. How do you ensure that every developer is working on the same local setup? Especially when both the local database and its config varies wildly from developer to developer?
This is where Docker really shines. With Docker you an ensure that each team member is working on exactly the same local dev environment which is a huge benefit. Trust yourself lucky if you haven’t learned this from personal experience.
Docker, Docker, Docker
So why use Docker? Because it simplifies configuring your own local dev environment. Because installing Postgres, Redis, and other dependencies locally is a nightmare. And because Docker ensures you work on exactly the same specs as other members of your team.
Docker is less about deployment and more about faithfully recreating your production environment locally. That’s where it shines.
I’ve written a short tutorial if you want to learn how to work with Django, Docker, and PostgreSQL. And I’m writing a book-length version of a professional Django project that uses it in Django for Professionals.
Interested in learning more Django? I’ve written 3 books!