Создание сайта на Django: урок 56, деплой сайта с помощью Docker на VDS
avatar
7 | (offline)
❤️‍🔥Notehunter Developer
Добавлено:
Категория: Руководства «Django»
Комментариев: 0

Установка Docker и Docker compose

После покупки и создания сервера, я подключился к нему и сразу же начал установку Docker и Docker compose. Следующие статьи и урок 55 по Django помогут Вам правильно развернуть Ваш Django проект.

После успешной установки Docker на сервер убеждаюсь, что все встало как надо:

Также проверяю версию Docker compose:

Перед деплоем я проверю, что файл requirements.txt содержит все необходимое:

gunicorn
amqp==5.1.1
asgiref==3.5.2
async-timeout==4.0.2
billiard==3.6.4.0
celery==5.2.7
click==8.1.3
click-didyoumean==0.3.0
click-plugins==1.1.1
click-repl==0.2.0
colorama==0.4.5
Deprecated==1.2.13
Django==4.1
django-ckeditor-5==0.2.0
django-cleanup==6.0.0
django-debug-toolbar==3.6.0
django-js-asset==2.0.0
django-mptt==0.13.4
django-recaptcha==3.0.0
django-taggit==3.0.0
kombu==5.2.4
packaging==21.3
Pillow==9.2.0
prompt-toolkit==3.0.31
psycopg2==2.9.3
pyparsing==3.0.9
pytils==0.4.1
pytz==2022.2.1
redis==4.3.4
six==1.16.0
sqlparse==0.4.2
tzdata==2022.2
vine==5.0.0
wcwidth==0.2.5
wrapt==1.14.1

Также, .env.prod я заполнил следующим образом:

DJANGO_SECRET_KEY=django-insecure-e5wl)ln9l6f2cyvu2vt*2=*nez(bq7qj5c(2m1bcbojxlql_jy
DJANGO_DEBUG=0
CSRF_TRUSTED_ORIGINS=http://45.84.227.139
ALLOWED_HOSTS=45.84.227.139
POSTGRES_USER=DeployUser
POSTGRES_PASSWORD=DeployPass
POSTGRES_DB=DeployDB
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
CELERY_BROKER_URL=redis://redis:6379/0
CELERY_RESULT_BACKEND=redis://redis:6379/0
REDIS_LOCATION=redis://redis:6379/1
RECAPTCHA_PUBLIC_KEY=6Lc3Z1AhAAAAACf7fWueWxIXWjH117-wgbXGhhkB
RECAPTCHA_PRIVATE_KEY=6Lc331AhAAAAAAOjLoGOWA_kljXQaYO2CxtGt0ro
EMAIL_HOST=ad.notehunter@yahoo.com
EMAIL_PORT=465
EMAIL_USE_SSL=1
EMAIL_HOST_USER=smtp.mail.yahoo.com
EMAIL_HOST_PASSWORD=sgagesdsfsgheqtr

Отлично. Дальше я запаковываю в архив zip наш проект Django проект:

Удаляю лишние файлы из архива: .idea, __pycache__

Содержимое архива: 

С помощью WinSCP я загружаю данный архив по пути /home/ на нашем VDS.

Также перехожу в каталог /home/ в терминале. 

И устанавливаю zip, unzip:

sudo apt install zip unzip

И разархивирую zip архив с помощью терминала:

unzip backend

На выходе получаю:

Архив можно удалять и в терминале переходить в каталог backend.

cd backend

Оттуда я запускаю докеризацию:

docker compose build

И после завершения процесса докеризации, установки зависимых модулей, мы переходим к этапу запуска:

docker compose up

С первого раза может не запуститься, выйдет ошибка (ВОЗМОЖНО):

Error response from daemon: failed to mkdir /var/lib/docker/volumes/backend_media/_data/images/avatars: mkdir /var/lib/docker/volumes/backend_media/_data/images/avatars: file exists

Пропускаем и заново вводим docker compose up

И получаем следующее:

[+] Running 5/5
 ⠿ Container redis          Recreated                                                                              0.1s
 ⠿ Container postgres       Recreated                                                                              0.1s
 ⠿ Container django         Created                                                                                0.0s
 ⠿ Container celery-worker  Recreated                                                                              0.1s
 ⠿ Container nginx          Created                                                                                0.0s
Attaching to celery-worker, django, nginx, postgres, redis
redis          | 1:C 01 Oct 2022 07:08:46.716 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis          | 1:C 01 Oct 2022 07:08:46.717 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
redis          | 1:C 01 Oct 2022 07:08:46.718 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis          | 1:M 01 Oct 2022 07:08:46.719 * monotonic clock: POSIX clock_gettime
redis          | 1:M 01 Oct 2022 07:08:46.722 * Running mode=standalone, port=6379.
redis          | 1:M 01 Oct 2022 07:08:46.723 # Server initialized
redis          | 1:M 01 Oct 2022 07:08:46.723 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis          | 1:M 01 Oct 2022 07:08:46.727 * Ready to accept connections
postgres       | The files belonging to this database system will be owned by user "postgres".
postgres       | This user must also own the server process.
postgres       |
postgres       | The database cluster will be initialized with locale "en_US.utf8".
postgres       | The default database encoding has accordingly been set to "UTF8".
postgres       | The default text search configuration will be set to "english".
postgres       |
postgres       | Data page checksums are disabled.
postgres       |
postgres       | fixing permissions on existing directory /var/lib/postgresql/data ... ok
postgres       | creating subdirectories ... ok
postgres       | selecting dynamic shared memory implementation ... posix
postgres       | selecting default max_connections ... 100
postgres       | selecting default shared_buffers ... 128MB
postgres       | selecting default time zone ... Etc/UTC
postgres       | creating configuration files ... ok
postgres       | running bootstrap script ... ok
postgres       | performing post-bootstrap initialization ... ok
nginx          | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
nginx          | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
nginx          | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
nginx          | 10-listen-on-ipv6-by-default.sh: info: /etc/nginx/conf.d/default.conf is not a file or does not exist
nginx          | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
nginx          | /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
nginx          | /docker-entrypoint.sh: Configuration complete; ready for start up
nginx          | 2022/10/01 07:08:50 [notice] 1#1: using the "epoll" event method
nginx          | 2022/10/01 07:08:50 [notice] 1#1: nginx/1.23.1
nginx          | 2022/10/01 07:08:50 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
nginx          | 2022/10/01 07:08:50 [notice] 1#1: OS: Linux 5.15.0-48-generic
nginx          | 2022/10/01 07:08:50 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
nginx          | 2022/10/01 07:08:50 [notice] 1#1: start worker processes
nginx          | 2022/10/01 07:08:50 [notice] 1#1: start worker process 22
postgres       | syncing data to disk ... ok
postgres       |
postgres       | initdb: warning: enabling "trust" authentication for local connections
postgres       | You can change this by editing pg_hba.conf or using the option -A, or
postgres       | --auth-local and --auth-host, the next time you run initdb.
postgres       |
postgres       | Success. You can now start the database server using:
postgres       |
postgres       |     pg_ctl -D /var/lib/postgresql/data -l logfile start
postgres       |
postgres       | waiting for server to start....2022-10-01 07:08:50.573 UTC [46] LOG:  starting PostgreSQL 13.4 (Debian 13.4-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
postgres       | 2022-10-01 07:08:50.575 UTC [46] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres       | 2022-10-01 07:08:50.586 UTC [47] LOG:  database system was shut down at 2022-10-01 07:08:50 UTC
postgres       | 2022-10-01 07:08:50.599 UTC [46] LOG:  database system is ready to accept connections
postgres       |  done
postgres       | server started
postgres       | CREATE DATABASE
postgres       |
postgres       |
postgres       | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/*
postgres       |
postgres       | 2022-10-01 07:08:51.337 UTC [46] LOG:  received fast shutdown request
postgres       | waiting for server to shut down....2022-10-01 07:08:51.340 UTC [46] LOG:  aborting any active transactions
postgres       | 2022-10-01 07:08:51.361 UTC [46] LOG:  background worker "logical replication launcher" (PID 53) exited with exit code 1
postgres       | 2022-10-01 07:08:51.373 UTC [48] LOG:  shutting down
postgres       | 2022-10-01 07:08:51.396 UTC [46] LOG:  database system is shut down
postgres       |  done
postgres       | server stopped
postgres       |
postgres       | PostgreSQL init process complete; ready for start up.
postgres       |
postgres       | 2022-10-01 07:08:51.530 UTC [1] LOG:  starting PostgreSQL 13.4 (Debian 13.4-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
postgres       | 2022-10-01 07:08:51.533 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres       | 2022-10-01 07:08:51.533 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres       | 2022-10-01 07:08:51.535 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres       | 2022-10-01 07:08:51.545 UTC [74] LOG:  database system was shut down at 2022-10-01 07:08:51 UTC
postgres       | 2022-10-01 07:08:51.555 UTC [1] LOG:  database system is ready to accept connections
nginx          | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
nginx          | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
nginx          | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
nginx          | 10-listen-on-ipv6-by-default.sh: info: /etc/nginx/conf.d/default.conf is not a file or does not exist
nginx          | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
nginx          | /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
nginx          | /docker-entrypoint.sh: Configuration complete; ready for start up
nginx          | 2022/10/01 07:12:35 [notice] 1#1: using the "epoll" event method
nginx          | 2022/10/01 07:12:35 [notice] 1#1: nginx/1.23.1
nginx          | 2022/10/01 07:12:35 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
nginx          | 2022/10/01 07:12:35 [notice] 1#1: OS: Linux 5.15.0-48-generic
nginx          | 2022/10/01 07:12:35 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
nginx          | 2022/10/01 07:12:35 [notice] 1#1: start worker processes
nginx          | 2022/10/01 07:12:35 [notice] 1#1: start worker process 22
django         |
django         | 0 static files copied to '/app/static', 273 unmodified.
celery-worker  | /usr/local/lib/python3.10/site-packages/celery/platforms.py:840: SecurityWarning: You're running the worker with superuser privileges: this is
celery-worker  | absolutely not recommended!
celery-worker  |
celery-worker  | Please specify a different user using the --uid option.
celery-worker  |
celery-worker  | User information: uid=0 euid=0 gid=0 egid=0
celery-worker  |
celery-worker  |   warnings.warn(SecurityWarning(ROOT_DISCOURAGED.format(
celery-worker  |
celery-worker  |  -------------- celery@c20bee835901 v5.2.7 (dawn-chorus)
celery-worker  | --- ***** -----
celery-worker  | -- ******* ---- Linux-5.15.0-48-generic-x86_64-with-glibc2.28 2022-10-01 10:12:37
celery-worker  | - *** --- * ---
celery-worker  | - ** ---------- [config]
celery-worker  | - ** ---------- .> app:         backend:0x7f131ecda650
celery-worker  | - ** ---------- .> transport:   redis://redis:6379/0
celery-worker  | - ** ---------- .> results:     redis://redis:6379/0
celery-worker  | - *** --- * --- .> concurrency: 1 (prefork)
celery-worker  | -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
celery-worker  | --- ***** -----
celery-worker  |  -------------- [queues]
celery-worker  |                 .> celery           exchange=celery(direct) key=celery
celery-worker  |
celery-worker  |
celery-worker  | [tasks]
celery-worker  |   . modules.system.services.tasks.db_backup_task
celery-worker  |   . modules.system.services.tasks.send_activate_email_task
celery-worker  |
django         | No changes detected
django         | Operations to perform:
django         |   Apply all migrations: admin, auth, blog, contenttypes, sessions, sites, system, taggit
django         | Running migrations:
django         |   Applying contenttypes.0001_initial... OK
django         |   Applying auth.0001_initial... OK
django         |   Applying admin.0001_initial... OK
django         |   Applying admin.0002_logentry_remove_auto_add... OK
django         |   Applying admin.0003_logentry_add_action_flag_choices... OK
django         |   Applying contenttypes.0002_remove_content_type_name... OK
django         |   Applying auth.0002_alter_permission_name_max_length... OK
django         |   Applying auth.0003_alter_user_email_max_length... OK
django         |   Applying auth.0004_alter_user_username_opts... OK
django         |   Applying auth.0005_alter_user_last_login_null... OK
django         |   Applying auth.0006_require_contenttypes_0002... OK
django         |   Applying auth.0007_alter_validators_add_error_messages... OK
django         |   Applying auth.0008_alter_user_username_max_length... OK
django         |   Applying auth.0009_alter_user_last_name_max_length... OK
django         |   Applying auth.0010_alter_group_name_max_length... OK
django         |   Applying auth.0011_update_proxy_permissions... OK
django         |   Applying auth.0012_alter_user_first_name_max_length... OK
django         |   Applying taggit.0001_initial... OK
django         |   Applying taggit.0002_auto_20150616_2121... OK
django         |   Applying taggit.0003_taggeditem_add_unique_index... OK
django         |   Applying taggit.0004_alter_taggeditem_content_type_alter_taggeditem_tag... OK
django         |   Applying taggit.0005_auto_20220424_2025... OK
django         |   Applying blog.0001_initial... OK
django         |   Applying blog.0002_category_article_category... OK
django         |   Applying blog.0003_article_meta_description_article_meta_keywords_and_more... OK
django         |   Applying blog.0004_comment... OK
django         |   Applying blog.0005_article_tags... OK
django         |   Applying blog.0006_alter_article_full_description_and_more... OK
django         |   Applying blog.0007_rating... OK
django         |   Applying sessions.0001_initial... OK
django         |   Applying sites.0001_initial... OK
django         |   Applying sites.0002_alter_domain_unique... OK
django         |   Applying system.0001_initial... OK
django         |   Applying system.0002_feedback... OK
django         | [2022-10-01 07:20:54 +0000] [10] [INFO] Starting gunicorn 20.1.0
django         | [2022-10-01 07:20:54 +0000] [10] [INFO] Listening at: http://0.0.0.0:8000 (10)
django         | [2022-10-01 07:20:54 +0000] [10] [INFO] Using worker: sync
django         | [2022-10-01 07:20:54 +0000] [11] [INFO] Booting worker with pid: 11
django         | [2022-10-01 07:20:54 +0000] [12] [INFO] Booting worker with pid: 12
django         | [2022-10-01 07:20:54 +0000] [13] [INFO] Booting worker with pid: 13
django         | [2022-10-01 07:20:54 +0000] [14] [INFO] Booting worker with pid: 14

И переходя на наш адрес: 45.84.227.139

Мы видим наш задеплоенный сайт, и результаты ответа Nginx:

Чтоб создать админскую учетку, можно в консоле ввести:

И дальше пользоваться нашим Django проектом :)

Комментарии к статье 0
Комментариев нет
Форма добавления комментария (необходима регистрация)