This is a continuation of (2) frontend development --Nginx + React.
I want to develop an application with Djagno + React configuration and deploy it to Google Kubernetes Engine I wrote it because it was unlikely that there was a cohesive tutorial.
However, ** I think there are some points that are not perfect yet **, but I think that if you have some experience, you can use it immediately.
This is a record of an inexperienced hobby engineer struggling to deploy to create a portfolio. If there are any deficiencies, please point them out. ..
$ node --version
v12.14.1
$ npm --version
6.13.7
$ python --version
Python 3.7.4
$ docker --version
Docker version 19.03.8
OS windows10 pro
We will deploy to Google Kubernetes Engine (GKE). I have a lot of reference to the Official Tutorial.
Log in to your Google account and start a new project from the Cloud console.
Project name: gke-django-tutorial
place:No organization
Reference: https://cloud.google.com/billing/docs/how-to/modify-project?authuser=2
GCP resources can be manipulated from your local PC using the Cloud SDK. It is assumed that gcloud is already installed.
#gcloud initialization
$\gke-django-tutorial\gcloud init
Welcome! This command will take you through the configuration of gcloud.
Pick configuration to use:
[1] Re-initialize this configuration [xxxxxx] with new settings
[2] Create a new configuration
Please enter your numeric choice: 2
Enter configuration name. Names start with a lower case letter and
contain only lower case letters a-z, digits 0-9, and hyphens '-': gke-django-tutorial
Your current configuration has been set to: [gke-django-tutorial]
You can skip diagnostics next time by using the following flag:
gcloud init --skip-diagnostics
Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).
Choose the account you would like to use to perform operations for
this configuration:
[1] [email protected]
[2] [email protected]
[3] Log in with a new account
Please enter your numeric choice: 1
You are logged in as: [[email protected]].
Pick cloud project to use:
[1] XXXXXXX
[2] [YOUR_PROJECT]
[3] Create a new project
Please enter numeric choice or text value (must exactly match list
item): 2
Your current project has been set to: [YOUR_PROJECT].
Not setting default zone/region (this feature makes it easier to use
[gcloud compute] by setting an appropriate default value for the
--zone and --region flag).
See https://cloud.google.com/compute/docs/gcloud-compute section on how to set
default compute region and zone manually. If you would like [gcloud init] to be
able to do this for you the next time you run it, make sure the
Compute Engine API is enabled for your project on the
https://console.developers.google.com/apis page.
Your Google Cloud SDK is configured and ready to use!
* Commands that require authentication will use [email protected] by default
* Commands will reference project `[YOUR_PROJECT]` by default
Run `gcloud help config` to learn how to change individual settings
This gcloud configuration is called [YOUR_PROJECT]. You can create additional configurations if you work with multiple accounts and/or projects.
Run `gcloud topic configurations` to learn more.
[Omitted below]
Enable Datastore, Pub / Sub, Cloud Storage JSON, Cloud Logging, and Google+ APIs.
$\gke-django-tutorial\gcloud services enable sqladmin
Operation "operations/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" finished successfully.
Download Cloud SQL Proxy and rename it to cloud_sql_proxy.exe
.
I installed it under $ \ gke-django-tutorial \
.
--Reference: Installing the Cloud SQL Proxy
Create an instance of CloudSQL from the Cloud console.
Database engine selection: PostgreSQL
Instance ID: [SQL_INSTANCE_NAME]
password: [YOUR_PASSWORD]
Location:
region: [SQL_REGION_NAME]
zone: [DATABASE_ZONE]
Database version: PostgreSQL 11
Check the connectionName
to connect to CloudSQL using the cloud_sql_proxy.exe
you downloaded earlier.
#Confirmation of connecsionName
$\gke-django-tutorial\gcloud sql instances describe [SQL_INSTANCE_NAME]
connectionName: [YOUR_PROJECT]:[SQL_REGION_NAME]:[SQL_INSTANCE_NAME]
#Instance connection
$\gke-django-tutorial\gcoud_sql_proxy.exe -instances="[YOUR_PROJECT]:[SQL_REGION_NAME]:[SQL_INSTANCE_NAME]"=tcp:5432
2020/04/28 17:49:51 Listening on 127.0.0.1:5432 for gke-django-tutorial:asia-northeast1:websql
2020/04/28 17:49:51 Ready for new connections
This command allowed me to connect to my CloudSQL instance from my PC. Leave the command prompt connected to your instance and work with another command prompt.
Let's create a database from the console. You can create a database
from a database
by selecting [SQL_INSTANCE_NAME]
on the console.
Database name: [DATABASE_NAME]
Create a database user account from the console.
username: [DATABASE_USER]
password: [DATABASE_PASSWORD]
Create a CloudSQl service account from the console and download your private key in json format.
Service account name: [SERVICE_ACCOUNT_NAME]
Service account ID: [SERVICE_ACCOUNT_NAME]@BBBBBBBBB.iam.gservice
Authority:Cloud SQL administrator
⇒ Select json format when creating a private key
⇒ json format private key: ZZZZZZZZZZZZZZZ.json is downloaded
Create a directory called secrets \ cloudsql \
directly under the project and place the created private key.
$\gke-django-tutorial\mkdir secrets
$\gke-django-tutorial\cd secrets
$\gke-django-tutorial\secrets\mkdir cloudsql
$\gke-django-tutorial\secrets\cd cloudsql
#Keep your private key
$\gke-django-tutorial\secrets\cloudsql\dir
ZZZZZZZZZZZZZZZ.json
Set up your Django database in CloudSQL, start it, and get ready to use CloudSQL. As we did in local sqlite3, we will migrate the table from the local environment through cloud_sql_proxy.
Add DATABASE_USER
and DATABASE_PASSWORD
to the .env
file to use them as environment variables.
Don't put a space between key and value.
SECRET_KEY='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
DEBUG=False
DATABASE_USER=[DATABASE_USER]
DATABASE_PASSWORD=[DATABASE_PASSWORD]
backend/config/settings.py
Change Django's DATABASE setting from db.sqlite3 to CloudSQL.
You need to reference the .env
file directly, so load it using python-dotenv
.
# backend/config/setting.sy
import os
from dotenv import load_dotenv #add to
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_DIR = os.path.basename(BASE_DIR)
load_dotenv(os.path.join(BASE_DIR, '.env')) #add to
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG')
DATABASES = {
'default': {
# If you are using Cloud SQL for MySQL rather than PostgreSQL, set
# 'ENGINE': 'django.db.backends.mysql' instead of the following.
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'web-db',
'USER': os.getenv('DATABASE_USER'),
'PASSWORD': os.getenv('DATABASE_PASSWORD'),
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
I changed the database settings to CloudSQL and need to migrate again.
(venv)$\gke-django-tutorial\backend\python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, todo
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK
Applying todo.0001_initial... OK
I was able to migrate to CloudSQL without any problems.
Create an admin user as well as sqlite.
(venv)$\gke-django-tutorial\backend\python manage.py createsuperuser
username(leave blank to use '[YOUR_NAME]'): [SUPERUSER_NAME]
mail address: [YOUR_EMAIL]@gmail.com
Password:
Password (again):
Superuser created successfully.
Let's start the development server and add about 3 data from the administrator page.
(venv)$\gke-django-tutorial\backend\python manage.py runserver
You can store data on the database created in your CloudSQL instance by logging in to the admin page at http: // localhost: 8000 / admin /
.
Let's add a few items.
Store static files in Google Cloud Storage (GCS), and configure settings for static files to be delivered from GCS.
Create storage and upload static files. If you do not do this, css such as admin screen will not be reflected.
#Creating storage
(venv)$\gke-django-tutorial\backend\gsutil mb gs://[STORAGE_NAME]
Creating gs://gke-django-storage/...
#Publishing Settings
(venv)$\gke-django-tutorial\backend\gsutil defacl set public-read gs://[STORAGE_NAME]
Setting default object ACL on gs://[STORAGE_NAME]/...
/ [1 objects]
#Collect static files
(venv)$\gke-django-tutorial\backend\python manage.py collectstatic
#Upload static files to Cloud Storage
(venv)$\gke-django-tutorial\backend\gsutil rsync -R staticfiles/ gs://[STORAGE_NAME]/static
Change STATIC_URL
in backend / config / settings.py
to refer to GCS.
# backend/config/settings.py
STATIC_URL = 'https://storage.googleapis.com/[STORAGE_NAME]/static/'
We created a GCP project and prepared for Cloud SQL and Cloud Storage.
⇒ (4) Cluster creation and container PUSH
Recommended Posts