Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build a Django+Mariadb environment for Docker

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to build Django+Mariadb environment in Docker". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to build Django+Mariadb environment in Docker".

Reading suggestions on setting up Django+Mariadb Environment by Docker

Read through the full text before deciding on the steps that need to be put into practice. Later, there is always a more concise, faster and better practice.

However, the newcomer's suggestion to practice from beginning to end can be regarded as a beautiful talk of "stupid ways to learn Docker".

The idea of this article is as follows:

Pull Mariadb image directly, set up database manual Build Django mirror: python2.7-based mirror allows us to do better: optimize "docker-v" & & "docker-- link" based on Python2.7-slim image

Source code: git@github.com:AnInputForce/autodepopy.git

Basically is to learn while the experiment, the key steps are commit. Please refer to it.

The "Docker-Mariadb" Construction of Environment

Reference: install Maridb directly in Mac (not recommended), installation steps of MariaDB database in Mac

First, install your host mac or linux with the tree command. No, it doesn't matter. If you have something related below, just change it to ls.

Download Mariadb database mirroring docker pull mariadb to start and configure DB

Map database data files and configuration files

Create a new ~ / mariadb/data, ~ / mariadb/custom directory

-v ~ / mariadb/data:/var/lib/mysql mapping data file out

-v ~ / mariadb/custom:/etc/mysql/conf.d mapping configuration file

Specify database code utf8mb4. Refer to: mysql experience hematemesis summary using utf8mb4

$mkdir-p ~ / mariadb/data ~ / mariadb/custom$ docker run-- name my-mariadb-v ~ / mariadb/data:/var/lib/mysql-v ~ / mariadb/custom:/etc/mysql/conf.d-p 3306 mariadb/custom$ docker run 3306-e MYSQL_ROOT_PASSWORD=1q2w-d mariadb:latest-- character-set-server=utf8mb4-- collation-server=utf8mb4_unicode_ci Test Verification $docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES77de3a6bf3fe mariadb:latest "docker-entrypoint..." 2 minutes ago Up About a minute 0.0.0.0 minutes ago Up About a minute 3306-> 3306/tcp my-mariadb$ docker exec-it my-mariadb bashroot@77de3a6bf3fe:/# mysql-uroot-p1q2wWelcome to the MariaDB monitor. Commands end with; or\ g.MariaDB [(none)] > show databases;+-+ | Database | +-+ | information_schema | | mysql | | performance_schema | +-+ 3 rows in set (0.02 sec) environment "Docker-Django" construction

Unexpectedly, I flipped through the official hub image and got the following prompt:

This image is officially deprecated in favor of the standard python image

This image has been replaced by a standard python image. This image cannot directly bring into the Django environment, and its only value is to provide some Django dependencies such as mysql-client. Perhaps because Django is APP-level, it depends on Project's requirements.txt,like this:

We can only do it ourselves and have plenty of food and clothing. Just in time to practice what I have just learned.

Prepare the project directory

Workspace Workspace, home of all projects: get used to it

Autodeploy automatic deployment project directory: get used to it

Z-dev stores the development environment dockerfile and related information: you are used to it

Z-pub stores production environment dockerfile and related information: I am used to

.dockerkeeper stores files that are not watched by the mirrored build: from Vscode. It is not visible under linux. For more information, please see github of this project.

$mkdir-p ~ / workspace/autodeploy & & cd ~ / workspace/autodeploy & & mkdir z-dev z-pub create Dockerfile

Use Python2.7 basic image directly, which is simple, rough and easy, and is suitable for children who want to experience it quickly:

# basic image FROM python:2.7# maintainer information MAINTAINER kang.cunhua # app directory WORKDIR / usr/local/webADD. / usr/local/web/# relies on RUN pip install to install app-- no-cache-dir-r requirements.txt to create the current directory structure of requirements.txtDjango==1.11.3MySQL-python host ChinaDreams:autodeploy kangcunhua$ tree. ├── readme.md ├── z-dev │ ├── Dockerfile │ └── requirements.txt └── z-pub └── Dockerfile2 directories, 4 filesBuild image

Current directory: ~\ workspace\ autodeploy

Cd z-dev & & docker build-t mydjango:latest. Check the image ChinaDreams:z-dev kangcunhua$ docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEmydjango latest 90a25c587400 23 seconds ago 699MB to start running & enter the container

Background start:-d parameter, enter the bash interface without adding it. Here for demonstration, first run-d background, and then exec to enter

ChinaDreams:z-dev kangcunhua$ docker run-- name web-it-p 8000 it 8000-d mydjango / bin/bash0b0e757708c29d0aa1799c14b6cd1f19a48e7cd748223064a0ab9205432ed23aChinaDreams:z-dev kangcunhua$ docker exec-it web / bin/bashroot@9326b308aacd:/usr/local/web# Clean and verify the environment

Clean up excess files

Root@9326b308aacd:/usr/local/web# lsrequirements.txtroot@9326b308aacd:/usr/local/web# rm *

Verification

Root@9326b308aacd:/usr/local/web# python-- versionPython 2.7.13root@9326b308aacd:/usr/local/web# python-m django--version1.11.3 scaffolding generation project, launch the web service root@26ad1dfb070f:/usr/web# django-admin startproject autodeployroot@26ad1dfb070f:/usr/web# cd autodeploy & & python manage.py runserver 0VOV 8000 browser access

Http://localhost:8000, is no surprise, you can see the legendary Django welcome page:

It worked!Congratulations on your first Django-powered page. Copy the project framework

CONTROL-C exits webserver; and then exits the container:

Root@9326b308aacd:/usr/local/web/autodeploy# exitexitChinaDreams:z-dev kangcunhua$ cd ~ / workspace & & docker cp web:/usr/local/web/autodeploy. & & cd autodeploy & & rm-rf db.sqlite3 & & tree. ├── autodeploy │ ├── _ _ init__.py │ ├── _ _ init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ ├── urls.pyc │ ├── wsgi.py │ └── wsgi.pyc ├── manage.py ├── readme.md z-dev │ ├── Dockerfile │ └── requirements.txt └── z-pub └── Dockerfile3 directories 13 files delete container web

At this point, the container mission has been completed: generate the project initialization directory and delete it.

ChinaDreams:autodeploy kangcunhua$ docker stop web & & docker rm web new container web, mount the local directory

The local directory overrides the container directory first, and then synchronizes in real time. PS: so it is difficult to mount a directory in the container at first. Why don't you copy out and empty it first. And then mount it locally.

"run-d" background starts, exec executes commands to start web server

ChinaDreams:autodeploy kangcunhua$ docker run-- name web-d-it-p 8000 it 8000-v / workspace:/usr/local/web mydjango / bin/bash2bf0f6d17f1d103a37a7992393e1f97483034cdadb01df6cf49ab4e1d8746f62ChinaDreams:autodeploy kangcunhua$ docker exec-it web / bin/bash-c "cd autodeploy&&python manage.py runserver 0vision 8000" run, harvest the Django welcome interface

Http://localhost:8000

It worked!Congratulations on your first Django-powered page.

Rejoice, boy!

What we need to be sober to make us do better is that there are the following questions

We are not using Mariadb at this time, and the default is the SqlLite database. Let's take a look at how to access the database from the web container

We use the base library of Python by default, and the volume of django has reached an astonishing 700m after installation.

When installing an image in docker pull, it is a tortoise speed: for well-known reasons

Installing the python module in pip install is about the same as turtle speed: for well-known reasons

Can we do better? The answer is, it must be!

Improve our Dockerfile# basic image FROM python:2.7-slim# maintainer information MAINTAINER kang.cunhua # app directory WORKDIR / usr/src/webADD. / usr/src/web# the dependency required to install app, do some cleaning work RUN buildDeps='gcc';\ deveDeps='mysql-client' \ set-x\ & & cp / etc/apt/sources.list / etc/apt/sources.list.backup\ & & mv sources.list / etc/apt/sources.list\ & & apt-get update & & apt-get install-y libmysqlclient-dev $buildDeps $deveDeps\ # When using Python 2.7, please install IPython 5.x LTS Long Term Support version. & & pip install-- no-cache-dir-r requirements.txt ipython==5.4.1\-I http://mirrors.aliyun.com/pypi/simple/-- trusted-host mirrors.aliyun.com\ & & rm-rf requirements.txt\ # remove gcc & & apt-get purge-y-- auto-remove $buildDeps

There are already a lot of comments, and some explanations for the new content are as follows:

Python:2.7-slim

Use a smaller slim image instead. One is to reduce the size of the build image, and the other is to start with the simplified version to review and consolidate the knowledge of Dockerfile.

Compared with the two built images, a lot of tools have been installed, and the image has reduced the size of 1max 2. The reason why the second image repository:tag is none is that the image we packaged this time also uses mydjango:latest.

ChinaDreams:z-dev kangcunhua$ docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEmydjango latest 8fee1723a96c 2 minutes ago 355MB 90a25c587400 About an hour ago 699MBsources.list

The image of python uses Debian, and the version is jessie. Found the accelerated image of Ariyun in China.

Deb http://mirrors.aliyun.com/debian/ jessie main non-free contribdeb http://mirrors.aliyun.com/debian/ jessie-proposed-updates main non-free contribdeb-src http://mirrors.aliyun.com/debian/ jessie main non-free contribdeb-src http://mirrors.aliyun.com/debian/ jessie-proposed-updates main non-free contribmirrors.aliyun.com

The python pip source of Aliyun is also used. You can specify the source of Aliyun during installation and trust it:

-I http://mirrors.aliyun.com/pypi/simple/-- trusted-host mirrors.aliyun.com install mysql-client

Because the "python manage.py dbshell" command requires. This command makes it easy to manipulate the database and automatically loads some environment variables; the development environment is still used; the build environment can be removed; if not installed, you will be prompted when you execute the command python manage.py dbshell

CommandError: You appear not to have the 'mysql' program installed or on your path. Install and uninstall gcc

Because the installation of MySQL-python depends on gcc. It is also said on the Internet that it can be solved by installing the MySQL-devel package, but it is not necessary for the time being, and there are also tips to install these python-devel mysql-devel zlib-devel openssl-devel, too many. Only install gcc, and then uninstall it after using it.

Compiling MySQL-python without installing gcc while build reports an error:

Unable to execute 'gcc': No such file or directoryerror: command' gcc' failed with exit status 1 install ipython==5.4.1

Because "python manage.py shell" is used to enter the interactive command line. It is not convenient to install. If you install ipython, you will automatically use their interface. Ipython is a set of enhanced interactive Shell that has been used all right; of course: the production environment can be installed without installation.

Start rebuilding preparation: create database ChinaDreams:autodeploy kangcunhua$ docker exec-d my-mariadb mysql-uroot-p1q2w-e "create database mydeploy;" prepare: modify DB configuration

Delete db.sqlite3, although previously deleted when copy, but the default configuration when running webserver is still sqlite3, so it is generated again.

Cd ~ / workspace/autodeploy & & rm db.sqlite3

Enter the web container and modify the DATABASES configuration in / autodeploy/autodeploy/settings.py:

Docker exec-it web / bin/bash

Because we have done local mapping, it is also valid to modify the corresponding configuration file directly with Vscode.

Note that in the 'HOST':' db', db is the alias we configured in link.

DATABASES = {'default': {' ENGINE': 'django.db.backends.mysql',' NAME': 'mydeploy',' USER': 'root',' PASSWORD': '1q2wages,' HOST': 'db',' PORT': '3306images,}} Build image

Current directory: ~\ workspace\ autodeploy

Cd z-dev & & docker build-t mydjango:latest. View mirrored ChinaDreams:z-dev kangcunhua$ docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEmydjango latest 90a25c587400 23 seconds ago 699MBWeb container to access Mariadb database

At this point, we have to mention the use of the "--link" command:

-link name:alias

Name is the name of our connection container, and alias is an alias for link. For example, if we connect to the web container of the database container, we can use alias to configure the database connection. See below: we link the database when we start the container:

Without this link, you will not be able to connect 127.0.0.1 link 3306 in the web container. Even if port 3306 is exposed

Start the database in the background (- d)

At this point, our database should be started. If docker ps finds that it is not started, it does not matter. Click the following command to start it:

Docker run-- name my-mariadb-v ~ / mariadb/data:/var/lib/mysql-v ~ / mariadb/custom:/etc/mysql/conf.d-p 3306-e MYSQL_ROOT_PASSWORD=1q2w-d mariadb:latest-- character-set-server=utf8mb4-- collation-server=utf8mb4_unicode_ci

Create a database mydeploy for the project. If there are any errors, check the log first.

Docker exec-d my-mariadb mysql-uroot-p1q2w-e "create database mydeploy;" docker logs my-mariadb launches web container link database container docker run-- name web-- link=my-mariadb:db-it-p 8000V ~ / workspace:/usr/src/web-d mydjango:latest / bin/bash e309fd9e718faf6629ce668860d5c9392c52da4f649f4307abf632a15b67285c authentication environment command

They are: check python version, check django version, enter dbshell operation database, enter ipython

Python-- versionpython manage.py-m django-- version./manage.py dbshell./manage.py shell creates an administrator

First migrate the database, then create the administrator

ChinaDreams:z-dev kangcunhua$ docker exec-it web/ bin/bashroot@e309fd9e718f:/usr/src/web# cd autodeploy/root@e309fd9e718f:/usr/src/web/autodeploy# python manage.py migrateroot@e309fd9e718f:/usr/src/web/autodeploy# python manage.py createsuperuser starts the web server

In the web container, execute

Python manage.py runserver 0:8000

Access on the host machine

Http://localhost:8000

You can see the legendary Django welcome page: "It works!" . Look at the database, and there are corresponding tables created.

Log in to the background, and you can also see the corresponding automatically generated page.

Http://localhost:8000/adminMySql client recommendation

By the way, Sequel Pro is recommended for MySQL or Mariadb clients under mac. It is free and super easy to use, which is easier to use than the official Oracle.

Can you do better?

The answer is: yes, you must! For example, we can introduce docker compose to create several microservices to integrate and direct the entire system architecture.

Let's introduce docker-compose

Docker-compse is a powerful tool for microservice management in our container cluster.

Revise dockerfile

Instead of using files to update the source, you can write the source of Ali Cloud directly with commands in dockfile to facilitate version management in git.

Give a complete dockerfile reference:

# basic image FROM python:2.7-slim# maintainer information MAINTAINER kang.cunhua # app directory WORKDIR / usr/local/webADD. / usr/local/web# the dependency required to install app, do some cleaning work RUN buildDeps='gcc';\ deveDeps='mysql-client' \ set-x\ & & mv / etc/apt/sources.list / etc/apt/sources.list.bak\ & & echo "deb http://mirrors.aliyun.com/debian/ jessie main non-free contrib" > / etc/apt/sources.list\ & & echo "deb http://mirrors.aliyun.com/debian/ jessie-proposed-updates main non-free contrib" > / etc/apt/sources.list\ & & echo "deb -src http://mirrors.aliyun.com/debian/ jessie main non-free contrib "> > / etc/apt/sources.list\ & & echo" deb-src http://mirrors.aliyun.com/debian/ jessie-proposed-updates main non-free contrib "> > / etc/apt/sources.list\ & & apt-get update & & apt-get install-y libmysqlclient-dev $buildDeps $deveDeps\ # When using Python 2.7 Please install IPython 5.x LTS Long Term Support version. & & pip install-- no-cache-dir-r requirements.txt ipython==5.4.1\-I http://mirrors.aliyun.com/pypi/simple/-- trusted-host mirrors.aliyun.com\ & & rm-rf requirements.txt\ # remove gcc & & apt-get purge-y-- auto-remove $buildDepsdockercompose.ymlversion: '2'services: db: image: mariadb expose:- "3306" volumes:-~ / mariadb/data:/var/lib/mysql-~ / mariadb/custom:/etc/mysql/conf.d environment:-MYSQL_DATABASE=mydeploy-MYSQL_ROOT_PASSWORD=1q2w-ON_CREATE_DB= "mydeploy"-COMPOSE_PROJECT_NAME=autodeploy command:-character-set-server=utf8mb4-- collation-server=utf8mb4_unicode_ci web: build: context:. Image: mydjango:latest volumes:-~ / workspace:/usr/local/web ports:-"8000 db command 8000" links:-db command: python. / autodeploy/manage.py runserver 0.0.0.0 workspace:/usr/local/web ports 8000 launch and access docker-compose upmigrateDB, Create administrator ChinaDreams:z-dev kangcunhua$ docker exec-it zdev_web_1 / bin/bashroot@e309fd9e718f:/usr/local/web# cd autodeploy/root@e309fd9e718f:/usr/local/web/autodeploy# python manage.py migrateroot@e309fd9e718f:/usr/local/web/autodeploy# python manage.py createsuperuser to verify the environment variable root@e309fd9e718f:/usr/local/web/autodeploy# python manage.py dbshellshow variables like 'character_set_database' Show variables like 'collation_%'; error command

Basically, commands that can be used by docker can also be used by docker-compose

Docker-compose up-d # background launch docker-compose logs # View micro service group log docker-compose ps # View micro service group container status specify Project name to launch

If not specified, the default container service name is "current directory _ service_number", such as "zdev_web_1". When specified as autoploy, it should become _ "autodeploy__web_1".

COMPOSE_PROJECT_NAME=autodeploy docker-compose updocker-compose-p autodeploy up access

Http://localhost:8000

Http://localhost:8000/admin

Because the previous database file is loaded, the previous one can still be used:

The account is the admin/root8888 created before.

Current file directory ChinaDreams:workspace kangcunhua$ tree. └── autodeploy ├── autodeploy │ ├── _ _ init__.py │ ├── _ _ init__.pyc ├── settings.py │ settings.pyc │ ├── urls.py │ ├── urls.pyc │ ├── wsgi.py │ └── wsgi.pyc ├── manage.py ├── readme.md ├── z-dev │ ├── Dockerfile │ ├── docker-compose.yml │ ├── requirements.txt │ └── sources.list └── z-pub └── Dockerfile4 directories 15 files reference list Mariadb is installed and configured under Docker

Reference: Start a mariadb server instance, highly recommended.

Reference: docker (6): building a mariadb database using dokcer

Install mariadb using the easiest way. And put the data under the / data/mysql/data directory of the host. Facilitate data backup, data migration, while exposing port 3306 to the outside. Using docker is still very convenient, and it is much easier to install and configure than yum. The configuration file can also be modified through directory mapping. And completely split the service, storage, interface. It's really a container.

Mac tree command

Reference: mac tree commands and parameters

$brew install treeDjango document

Getting Started

Writing your first Django app, part 1

Writing your first Django app, part 2

Thank you for reading, the above is the content of "how to build the Django+Mariadb environment for Docker". After the study of this article, I believe you have a deeper understanding of how to build the Django+Mariadb environment for Docker, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report