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 use docker-compose to deploy services

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

Today, I will talk to you about how to use docker-compose to deploy services. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something from this article.

Using docker-compose to deploy services starts with docker.

I know that some friends who read this article may not understand or use docker, so I will make a little introduction here. For those who already know, please read directly from the docker-compose section.

Introduction to docker

If you want to understand what docker is, you have to talk about what docker can solve.

In a word,

Docker is a container technology used to quickly deploy services

Why is docker a rapid deployment?

When we do a project, the last thing we want to face is not development or debugging, but deployment!

For example, the environment on your machine is python3, and you use python2 on another machine, or there is no python environment at all.

All right, how do you solve it at this time? Yes, as long as you go to the new machine, you have to deploy python.

Um ~ OK, deploy python on python, but you also need to use MySQL in your project, OK, you have to use pip to install the mysql module of python. Oh, by the way, I remember that our project also has redis, two kinds of asymmetric encryption, and three-party queues. Oh, and the interface of Aliyun, right. There are really a lot of messy things, which are gone after a few hours, and if you encounter a network card, there will be even less spectrum.

All right, we've evolved into a fast 1.0 era.

Let's put everything we want to install into the offline installation package and write a bash script

Yes, this kind of thing really happened. Deployment depends on a bash script, after all, there is no need to manual. But it is hard for the script writer, I have written a script for a long time.

So, we evolved again, in the era of Fast 2.0.

We made a mirror image of the whole system and stored it in the CD. Whenever we want to set up, we quickly use the image to make a new system!

May have experienced naturally will understand, but also to do a fucking mirror ah, how to do far away from the computer room! We play games, start the service quickly, update faster! What if our version is updated too fast! Do we still have to carve it? Our tornado has been updated again, I will go, and our client protobuf has also been updated, but we have 100 servers, ah, are we updated for this little thing? West eight!

So, once again, we join the glorious evolution, the fast 3.0 era.

We installed the service into docker

We made a good image, a command pull down, um, pretty soon another command docker start XXXXXX service. Oh, did you say multi-service? All right, then write a docker-compose.file. Mm-hmm? You said that the cluster deployment comes, there are Kubernetes, Mesos,Fleet and Swarm for you to choose, it is not easy to use and free of charge.

Docker is the best aid for deployment, and even if you are rotten to pieces, docker can help you to become the king.

Docker installation

It's very simple. Docker official website.

Cymbal

After Get docker, there is a next step for those who have graphic systems (such as windows). There is a term interface. There is software management like apt-get.

The installation is so simple that it's not worth talking about.

Some conceptual mirrors of docker

Yes! Just like what I said above, we already have an image using a CD copy, our image refers to a system image.

Our images are all based on linux, to be exact, based on ubuntu.

A docker image can be understood as a disk image that you copied with ghost under win. But he's the linux version.

Performance loss

Thanks to the namespace of the current linux kernel, we can have all kinds of containers for direct internal friction. Your process in docker is actually a direct host process, all of which is decided when the system starts the clone function, so there is no performance loss.

Container

Container itself is our most important concept, and what we need to do with docker is the container.

Simply put, the container is a mirrored instance

More generally, a container is like a virtual machine instance that you create with vm or virtualbox using images.

Hub

It's the mirror warehouse.

If you write code, you must know github, and we host the code on github.

If we deploy, I will definitely use dockerhub, and we will host the image on dockerhub (of course, we can also assume, or use the hub assumed by others)

There are many three-party dockerhub servers in China, including Ali Yun, NetEase Honeycomb, Rongyun, daocloud and so on.

As for foreign countries, it is even more, if you have to recommend one, it is amazon, after all, cloud services in their universe is the strongest, there is no one, there is no rival.

Docker simply uses search images

Docker search xxx

For example, if I want to set up a wordpress, I will use it directly.

Docker search wordpress

Root@ubuntu:~# docker search wordpressNAME DESCRIPTION STARS OFFICIAL AUTOMATEDwordpress The WordPress rich content management syst... 1574 [OK] appcontainers/wordpress Centos/Debian Based Customizable Wordpress... 34 [OK] bitnami/wordpress Bitnami Docker Image for WordPress 30 [OK] centurylink/wordpress Wordpress image with MySQL removed. 12 [OK] trafex/wordpress Wordpress container with Nginx 1.10 & PHP-... 5 [OK] maximiliend/wordpress An enhanced docker image of WordPress with... 4 [OK] devgeniem/wordpress-server Minimal wordpress server with nginx and ph... 3 [OK] scjalliance/wordpress WordPress with GD and FreeType 2 [OK] dsifford/wordpress A WordPress docker environment that just w... 2 [OK] bakudankun/wordpress-ja WordPress Japanese Edition forked from off... 1 [OK] ddaishin/wordpress Wordpress the latest version of Xdebug OSX... in Japan 1 [OK] dsteinkopf/wordpress wordpress clone plus some php extensions 1 [OK] nitra/wordpress nitra/wordpress image 0 [OK] miqueladell/wordpress Just a tailor made Wordpress. 0 [OK] ikoptiev/wordpress Official Wordpress image with max file upl... 0 [OK] tagplus5/wordpress wordpress 0 [OK] rwindegger/wordpress A wordpress php-fpm backend. 0 [OK] appeine/wordpress Container holding WordPress sources 0 [OK] wppier/wordpress wordpress-php7.0-fpm-alpine 0 [OK] svendocker/wordpress wordpress + mcrypt and recode 0 [ OK] indiehosters/wordpress WordPress image for IndieHosters service 0 [OK] derjudge/wordpress 1:1 clone of docker-library/wordpress with... 0 [OK] momonga/wordpress wordpress with mbstring, sendmail 0 [OK] deardooley/wordpress Production-ready minimal Wordpress images. 0 [OK] bearbeer/wordpress Wordpress with ssmtp. 0 [OK] root@ubuntu:~#

The first column is the image you can choose to use, of course you can make it yourself, and it's easy, but if we get started, let's just use someone else to do it.

Download the image

I'll just use the first one.

Git pull wordpress

This is in the process of downloading the image

Root@ubuntu:~# docker pull wordpressUsing default tag: latestlatest: Pulling from library/wordpress693502eb7dfb: Pull complete 16328c296404: Pull complete 8b3c97761df6: Pull complete 5e1d4f4f29eb: Pull complete 530750fc5019: Extracting [= = >] 1.252 kB/1.252 kB39e9c6c72db7: Download complete de476ce7ac87: Download complete 4ad13cbbc7d8: Download complete 74c28aa07dc7: Download complete a07a242e36fb: Download complete 3d491d166e88: Download complete cb6c232330f0: Download complete 25a48aec9dc7: Download complete 836344dc17d7: Download complete f5cafd105c82: Download complete fef842449a96: Download complete 9b13cded57f6: Download complete 0733368296e4: Download complete

Download completed

Root@ubuntu:~# docker pull wordpressUsing default tag: latestlatest: Pulling from library/wordpress693502eb7dfb: Pull complete 16328c296404: Pull complete 8b3c97761df6: Pull complete 5e1d4f4f29eb: Pull complete 530750fc5019: Pull complete 39e9c6c72db7: Pull complete de476ce7ac87: Pull complete 4ad13cbbc7d8: Pull complete 74c28aa07dc7: Pull complete a07a242e36fb: Pull complete 3d491d166e88: Pull complete cb6c232330f0: Pull complete 25a48aec9dc7: Pull complete 836344dc17d7: Pull complete f5cafd105c82: Pull complete fef842449a96: Pull complete 9b13cded57f6: Pull complete 0733368296e4: Pull complete Digest: sha256:498509cc3778374f65037f8dae67bb660d4fe650e8ac2129135224d5d2d81726Status: Downloaded newer image for wordpress:latesthelloworld

The old routine of programmers.

Root@ubuntu:~# docker run wordpress echo "hello world" hello world

This sentence is actually equivalent to your mirror image.

If you do helloworld, you'll be getting started. Ha ha ha.

Recommend a very hierarchical tutorial for getting started with docker

My usual docker command

You can use help to get an overview of a command.

Docker # docker command helps Commands: attach Attach to a running container # the attach connection under the current shell specifies the running image build Build an image from a Dockerfile # submit the current container as the new image cp Copy files/folders from the containers filesystem to the host path through Dockerfile custom image cp Copy files/folders from the containers filesystem to the host path # copy the specified file or directory from the container to the host create Create a new container # create a new container Same as run But do not start container diff Inspect changes on a container's filesystem # View docker container changes events Get real time events from the server # get container real-time events from docker service exec Run a command in an existing container # run the command export Stream the contents of a container as a tar archive # on an existing container to export the contents of the container Stream as a tar archive [corresponding import] history Show the history of an image # shows an image formation history images List images # lists the system's current image import Create a new filesystem image from the contents of a tarball # creates a new file system from the contents of the tar package Unified image [corresponding export] info Display system-wide information # display system related information inspect Return low-level information on a container # View container details kill Kill a running container # kill specify docker container load Load an image from a tar archive # load an image from a tar package [to Should save] login Register or Login to the docker registry server # register or log in to a docker source server logout Log out from a Docker registry server # exit from the current Docker registry logs Fetch the logs of a container # output the current container log information port Lookup the public-facing port which is NAT-ed to PRIVATE_PORT # View the internal source port pause Pause all processes within a container of the container corresponding to the mapped port # pause the container ps List containers # list the container list pull Pull an image or a repository from the docker registry server # pull the specified image or library image push from the docker image source server Push an image or a repository to the docker registry server # push the specified image or library image to the docker source server restart Restart a running container # restart the running container rm Remove one or more containers # remove one or more container rmi Remove one or more images # remove one or more images [this image can only be deleted without containers Otherwise, you need to delete the relevant container to continue or-f force delete] run Run a command in a new container # create a new container and run a command save Save an image to a tar archive # Save an image as a tar package [corresponding load] search Search for an image on the Docker Hub # search in docker hub Image start Start a stopped containers # start the container stop Stop a running containers # stop the container tag Tag an image into a repository # tag the image in the source top Lookup the running processes of a container # to view the process information unpause Unpause a paused container running in the container # Unpause container version Show the docker version information # check docker version number wait Block until a container stops Then print its exit code # intercepts the exit status value Run 'docker COMMAND-- help' for more information on a command when the container stops. Log in

Log in to your own dockerhub account and register.

Come to docker hub to register.

Docker login

View the container

Check the image you have downloaded

Docker images

Find Mirror

Docker search XX

Download the image

Docker pull xx

Delete Mirror

Docker rmi xx

Start

Docker run your mirror image

Read the log.

Docker logs, your container.

Stop a container example

Docker stop, your container.

View container status

Docker stats, your container.

Format

It's basically this format, and it's easy to use according to the notes written above.

Faster, better and stronger.

Use dockerfile

Use crontab

Use supervisr

Slightly, this is too long to pull.

Introduction to docker-compose

In a word

Docker-compose is a multi-container control for docker.

What is docker-compose?

Docker-compose is a thing used to automate docker.

With docker-compose, you can automate all the complicated docker operations with one command.

Why use docker-compose? what did he solve?

In popular language, we usually operate docker is still a very primitive series of actions, you manually use docker actions can be divided into

Find a system image / / docker search

Install vm or virtual box / / apt-get install docker

Install the image / / docker run-d-it your image in vm

Slightly; slightly.

This is the minimum action, if you want to map the hard drive, set up the nat network or bridge the network, etc. You have to do more docker operations, which is obviously very inefficient.

But it would be good if we wrote it in docker-compose.file. All you have to do is write it and run it.

Docker-compose up-d

Everything is so simple.

So where can I buy it?

If you can access the Internet, you can get him everywhere.

I have a python&pip environment on my own machine, so my installation is very simple.

Make sure you have docker installed first.

There is no installation. Please see the above article.

My environment is

Linux-ubuntu:python2:pip

So my installation

Pip install docker-compose

It's so simple

Start with a small example: root@ubuntu:~/test# cat docker-compose.yml version: '2'services: mariadb: image:' bitnami/mariadb:latest' environment:-ALLOW_EMPTY_PASSWORD=yes volumes:-/ path/to/mariadb-persistence:/bitnami/mariadbroot@ubuntu:~/test# docker-compose upCreating network "test_default" with the default driverCreating test_mariadb_1Attaching to test_mariadb_1mariadb_1 | mariadb_1 | Welcome to the Bitnami mariadb containermariadb_1 | Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-mariadbmariadb_1 | Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-mariadb/issuesmariadb_1 | Send us your feedback at containers@bitnami.commariadb_1 | mariadb_1 | nami INFO Initializing mariadbmariadb_1 | mariadb INFO = > Creating 'root' user with unrestricted access...mariadb_1 | mariadb INFO = > Flushing privileges...mariadb_1 | mariadb INFO = = > Enabling remote connections... Mariadb_1 | mariadb INFO mariadb_1 | mariadb INFO # mariadb_1 | mariadb INFO Installation parameters for mariadb:mariadb_1 | mariadb INFO Root Password: Not set during installationmariadb_1 | mariadb INFO (Passwords Are not shown for security reasons) mariadb_1 | mariadb INFO # mariadb_1 | mariadb INFO mariadb_1 | nami INFO mariadb successfully initializedmariadb_1 | INFO = = > Starting mariadb...mariadb_1 | 2017-03- 15:01:27 139903487235968 [Note] InnoDB: Highest supported file format is Barracuda.mariadb_1 | 2017-03-05 15:01:27 139903487235968 [Note] InnoDB: 128rollback segment (s) are active.mariadb_1 | 2017-03-05 15:01:27 139903487235968 [Note] InnoDB: Waiting for purge to startmariadb_1 | 2017-03-05 15:01:27 139903487235968 [Note] InnoDB: Percona XtraDB (http://www.percona.com) 5.6.34-79.1 started) Log sequence number 1616829mariadb_1 | 2017-03-05 15:01:27 139902956046080 [Note] InnoDB: Dumping buffer pool (s) not yet started install first

If your environment is the same as mine, please look directly at my docker-compose installation

If it's something else, don't worry, it's here.

Installation Guid

Helloworldroot@ubuntu:~/test# cat docker-compose.yml version: '2'services: mariadb: image:' bitnami/mariadb:latest' environment:-ALLOW_EMPTY_PASSWORD=yes volumes:-/ path/to/mariadb-persistence:/bitnami/mariadb command: echo "helloworld" root@ubuntu:~/test# root@ubuntu:~/test# root@ubuntu:~/test# docker-compose up Starting test_mariadb_1Attaching to test_mariadb_ 1mariadb_1 | mariadb_1 | Welcome to the Bitnami mariadb containermariadb_1 | Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-mariadbmariadb_1 | Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-mariadb/issuesmariadb_1 | Send us your feedback at containers@bitnami.commariadb_1 | mariadb_1 | hello worldtest_mariadb_1 exited with code 0 service update soft upgrade $docker-compose stop wordpress stop container running $docker-compose rm wordpress delete In addition to the old container update your image$ docker-compose start wordpress start the new container

And for example,

After your nginx updates the configuration file

Docker-compose restart nginx

Hard upgrade

Docker-compose stop

Upgrade your program

You need to start over.

Docker-compose up

Get the information you need from the log and use logs directly

Docker-compose logs nginx

O shit just maxed out my screen.

Use a similar linux tail command

What does our tial command usually look like?

Tail-f xx.file

Our docker-compose log is like this.

Root@ubuntu:~# docker-compose logs-f-tail 10 nginx

Attaching to root_nginx_1

Nginx_1 | 64.79.100.22-[05/Mar/2017:16:57:18 + 0000] "GET / wp-admin/ HTTP/1.1" 3020 "http://www.yunlan.name/wp-admin/"" Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 "

Nginx_1 | 64.79.100.22-- [05/Mar/2017:16:57:18 + 0000] "GET / wp-login.php?action=lostpassword HTTP/1.1" 1201 "http://www.yunlan.name/wp-login.php?action=lostpassword"" Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 "

Nginx_1 | 64.79.100.22-- [05/Mar/2017:16:57:18 + 0000] "GET / wp-login.php?action=lostpassword HTTP/1.1" 1201 "-"Mozilla"

Nginx_1 | 64.79.100.22-- [05/Mar/2017:16:57:18 + 0000] "GET / wp-login.php?redirect_to=http%3A%2F%2Fwww.yunlan.name%2Fwp-admin%2F&reauth=1 HTTP/1.1" 1265 "http://www.yunlan.name/wp-admin/"" Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 "

Nginx_1 | 64.79.100.22-- [05/Mar/2017:16:57:19 + 0000] "GET / wp-login.php?redirect_to=http%3A%2F%2Fwww.yunlan.name%2Fwp-admin%2F&reauth=1 HTTP/1.1" 1265 "-"Mozilla"

Nginx_1 | 117.150.55.119-- [05/Mar/2017:16:57:52 + 0000] "GET / robots.txt HTTP/1.1" 200 134 "-" Mozilla/5.0 (Macintosh; Intel Mac OS X 1012 / 3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 "

Nginx_1 | 117.150.55.119-- [05/Mar/2017:16:58:03 + 0000] "GET / HTTP/1.1" 499 0 "-" Mozilla/5.0 (Macintosh; Intel Mac OS X 10-12-3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 "

Nginx_1 | 117.150.55.119-- [05/Mar/2017:16:58:03 + 0000] "GET / HTTP/1.1" 200 3844 "-" Mozilla/5.0 (Macintosh; Intel Mac OS X 10-12-3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 "

Nginx_1 | 117.150.55.119-- [05/Mar/2017:16:58:03 + 0000] "GET / wp-content/plugins/code-prettify/prettify/run_prettify.js?ver=1.3.4 HTTP/1.1" 200 7600 "http://www.yunlan.name/"" Mozilla/5.0 (Macintosh; Intel Mac OS X 10 / 12 / 3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 "

Nginx_1 | 117.150.55.119-- [05/Mar/2017:16:58:04 + 0000] "GET / wp-content/plugins/code-prettify/prettify/prettify.css HTTP/1.1" 200 722 "http://www.yunlan.name/"" Mozilla/5.0 (Macintosh; Intel Mac OS X 10 / 12 / 3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 "

The last 10 started.

Docker-compose common commands Commands: build Build or rebuild services bundle Generate a Docker bundle from the Compose file config Validate and view the compose file create Create services down Stop and remove containers, networks, images And volumes events Receive real time events from containers exec Execute a command in a running container help Get help on a command kill Kill containers logs View output from containers pause Pause services port Print the public port for a port binding ps List containers pull Pull service images push Push service images restart Restart services rm Remove stopped containers run Run an one-off command scale Set number of containers for a service start Start services stop Stop services top Display the running processes unpause Unpause services up Create and start containers version Show the Docker-Compose version information

Explain

Build build or rebuild service help command helps kill kill container logs display container output port print bound open port ps display container pull pull service mirror restart restart service rm delete stopped container run run an one-time command scale set the number of containers of the service start open service stop stop service up create and start container docker-compose how to configure

Let's take a look at a docker-compose.yml I wrote myself.

Version: '2'services: nginx: image: bitnami/nginx:latest ports: -' 80 nginx'- '1443 version:-/ root/wp_yunlan/nginx/:/bitnami/nginx/ mariadb: image: bitnami/mariadb:latest volumes: -/ root/wp_yunlan/mariadb:/bitnami/mariadb wordpress: image: bitnami/wordpress:latest depends_on:-mariadb-nginx environment:-WORDPRESS_USERNAME=neptunemoon # you set up this account yourself-WORDPRESS_PASSWORD=123123 # this password The code is ports:-'8080 root/wp_yunlan/apache:/bitnami/apache 80'-'8081 root/wp_yunlan/apache:/bitnami/apache 443' volumes:-/ root/wp_yunlan/wordpress:/bitnami/wordpress-/ root/wp_yunlan/apache:/bitnami/apache-/ root/wp_yunlan/php:/bitnami/php

Nginx and mariadb,wordpress are the three services to be started

The order is not important. We see an attribute of depends_on: in wordpress.

Depends_on: dependency

It means that wordpress depends on

-mariadb- nginx

Two services, so the two of them will start first

Image: mirroring

Is your docker image.

We use

Docker search mariadb

Find the mirror image we need.

Root@ubuntu:~/test# docker search mariadbNAME DESCRIPTION STARS OFFICIAL AUTOMATEDmariadb MariaDB is a community-developed fork of M... 1192 [OK] paintedfox/mariadb A docker image for running MariaDB 5.5, a... 29 [OK] bitnami/mariadb Bitnami MariaDB Docker Image 29 [OK] million12/mariadb MariaDB 10 on CentOS-7 with UTF8 defaults 12 [OK] toughiq/mariadb-cluster Dockerized Automated MariaDB Galera Cluste... 9 [OK] webhippie/mariadb Docker images for mariadb 6 [OK] panubo/mariadb-galera MariaDB Galera Cluster 6 [OK] kakilangit/mariadb Docker for MariaDB with OQGraph & TokuDB E. 5 [OK] maxexcloo/mariadb Service container with MariaDB installed a... 4 [OK] tcaxias/mariadb MariaDB containers 1 [OK] desertbit/mariadb This is an extended docker image of the of... 1 [OK] russmckendrick/mariadb A MariaDB image 1 [OK] drupaldocker/mariadb MariaDB for Drupal 1 [OK] jpco/mariadb Mariadb So I can have it on my raspberry 1 [OK] clearlinux/mariadb MariaDB Server 1 [OK] danielsreichenbach/mariadb Minimal MariaDB container to be used as co... 0 [OK] lucidfrontier45/mariadb Mariadb with some customizable properties 0 [OK] codete/mariadb MariaDB docker image used at Codete. 0 [OK] dogstudio/mariadb MariaDB Container for Dogs 0 [OK] babim/mariadb Mariadb Server on Alpine or Debian. Check... 0 [OK] objectstyle/mariadb ObjectStyle MariaDB Docker Image 0 [OK] oriaks/mariadb MariaDB 0 [OK] yannickvh/mariadb Custom build of MariaDB based on the offic... 0 [OK] gymnae/mariadb Alpine based simple mariadb 0 [OK] nimmis/mariadb MariaDB multiple versions based on nimmis/... 0 [OK] root@ubuntu:~/test#

All right, it's bitnami/mariadb.

If you see that there is not an images, but a build, that means that this is not mirrored, but uses dockerfile to build the container.

If it's going to take a long time to say dockerfile,

If you want to know more about dockerfile, you can see it here.

Write Dockerfile

Environment environment variable

This is easy to understand.

However, this is not the same as our programming language design level, this is the container level environment variable.

If we write programs to make some logical judgments, we will certainly use

For example, if we judge the current compiler, we will use

# if _ _ GNUC__ or # if _ MSC_VER

Accordingly, there must be such logic in our container that we often use environment variables to pass values, or to define a behavior. Anyone who has written a program knows it.

Ports Port Mappin

The mapping machine also has a mirrored port. There's nothing to say about this.

Volumes file mapping

There are two formats

Can correspond to-v my/path/:/docker/path in docker operation

You can also use the unilateral-v / path

This is equivalent to an anonymous mapping, in fact, there is a corresponding directory on the machine.

Use docker inspect-f {{.volumes}} / path to see the details

More in-depth understanding of Docker Volume than this

What docker-compose needs to pay attention to

Based on my own experience, I give a few points to pay attention to.

Don't use docker as a data container. Data must be placed outside the container using volumes.

Do not expose the docker-compose file to others, because it contains your server information

Use docker-compose commands instead of docker manual commands & docker-compose to operate at the same time.

Write a script class that automatically backs up the data mapped by docker.

Do not put all services in one docker container

Set a requirement to meet the requirements

I assume that what we need now is to build a blog system.

Our first impression must be wordpress, there is nothing more professional than this, of course, there are many, let's use django

Those who have used django will surely know that django starts with a construction project.

And data and so on.

We draw up a process.

Python environment building

Django environment building

Docker-compose.yml writing

Django construction project

Django database settings

Start running

Database synchronization

Build a simple stand-alone deployment python environment

Dockerfile

ENV PYTHONUNBUFFERED 1RUN mkdir / root/testdjango/code # all write absolute paths, so be careful not to be like me. WORKDIR / root/testdjango/codeADD requirements.txt / root/testdjango/code/RUN pip install-r requirements.txtADD. / root/testdjango/code/

Python's pip has a requirements.txt file specifically for environment-dependent

Django environment building

Requirements.txt

Djangopsycopg2docker-compose.yml writes db: image: postgresweb: build:. Command: python manage.py runserver 0.0.0.0 volumes 8000 volumes: -.: / code ports:-"8000 volumes 8000" links:-dbdjango Construction Project

Docker-compose run web django-admin.py startproject docker_composeexample.

Django database settings

We did volumes, and django's things are mapped locally.

Anyone who has done django knows that our settings are all in settings.py.

Root@ubuntu:~/testdjango/docker_composeexample# cat settings.py "" Django settings for docker_composeexample project.Generated by 'django-admin startproject' using Django 1.10.6.For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/"""import os# Build paths inside the project like this: os.path.join (BASE_DIR .) BASE_DIR = os.path.dirname (os.path.dirname (os.path.abspath (_ _ file__) # Quick-start development settings-unsuitable for production# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secretly securely key ='3 percent crushing color% 9 grams nu2 percent 3x _ ^ g (vy2463d6'# SECURITY WARNING: don't run with debug turned on in) Productionmakers debug = TrueALLOWED_HOSTS = [] # Application definitionINSTALLED_APPS = ['django.contrib.admin' 'django.contrib.auth',' django.contrib.contenttypes', 'django.contrib.sessions',' django.contrib.messages', 'django.contrib.staticfiles',] MIDDLEWARE = [' django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',' django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',' django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' 'django.middleware.clickjacking.XFrameOptionsMiddleware',] ROOT_URLCONF =' docker_composeexample.urls'TEMPLATES = [{'BACKEND':' django.template.backends.django.DjangoTemplates', 'DIRS': [],' APP_DIRS': True, 'OPTIONS': {' context_processors': ['django.template.context_processors.debug' 'django.template.context_processors.request',' django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages',],},} ] WSGI_APPLICATION = 'docker_composeexample.wsgi.application'# Database# https://docs.djangoproject.com/en/1.10/ref/settings/#databasesDATABASES = {' default': {'ENGINE':' django.db.backends.sqlite3', 'NAME': os.path.join (BASE_DIR,' db.sqlite3') }} # Password validation# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validatorsAUTH_PASSWORD_VALIDATORS = [{'NAME':' django.contrib.auth.password_validation.UserAttributeSimilarityValidator',}, {'NAME':' django.contrib.auth.password_validation.MinimumLengthValidator',}, {'NAME':' django.contrib.auth.password_validation.CommonPasswordValidator',} {'NAME':' django.contrib.auth.password_validation.NumericPasswordValidator',},] # Internationalization# https://docs.djangoproject.com/en/1.10/topics/i18n/LANGUAGE_CODE = 'en-us'TIME_ZONE =' UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, JavaScript Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/STATIC_URL ='/ static/'root@ubuntu:~/testdjango/docker_composeexample#

We only set up the database

DATABASES = {'default': {' ENGINE': 'django.db.backends.postgresql_psycopg2',' NAME': 'postgres',' USER': 'postgres',' HOST': 'db',' PORT': 5432,}} start running

Docker-compose up

Database synchronization

Docker-compose run web python manage.py syncdb

After reading the above, do you have any further understanding of how to use docker-compose to deploy services? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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