Using virtualenv in production

10 February 2014

One of my favorite things about Python is being able to use virtualenv to create isolated environments. It’s extremely simple to use and allows you to have different versions of Python libraries used by different projects.

The thing that’s tricky is getting virtualenv set up on a production environment under different services since each one requires a slightly different configuration. I’ve gone through my projects and collected the various ways I’ve gotten it running for different services. I’m sure I could have done it differently but the following worked for me and will hopefully come in handy to others. If you have any questions or I’m not being clear enough let me know and I’ll updat the post with more information.

Nginx and Gunicorn under Supervisor.

Nginx - The configuration isn't anything different than normal except that you may need to specify some specific paths that are within your virtualenv

In this case we just configure Supervisor to start virtualenv path for celery. A cool feature is being able to specify the environment variables - in my case to pass in the Django settings module.

[program:celery]; Set full path to celery program if using virtualenv
command=/home/ubuntu/myapp/venv/bin/celery worker -A myapp --loglevel=INFOdirectory=/home/ubuntu/myappuser=nobodynumprocs=1stdout_logfile=/var/log/celery/worker.logstderr_logfile=/var/log/celery/worker.logautostart=trueautorestart=truestartsecs=10environment=DJANGO_SETTINGS_MODULE=myapp.settings.prod