Docker
Good Monday morning! Over the weekend, there was a comment to my previous post coveringusing Ansible to build Docker imagesfromMichael DeHaan, CTO and creator ofAnsible(thank you!) reminding me of his work discussed in his blog postInstalling and Building Docker with Ansiblethat is definitely worth sharing and the method I first used to build Docker images and wrotemy first rolethat will be shared in this post.
For the reader just joining, the previous posts in this series "Docker: Containers for the Masses" are:
- Introduction-- Introduction toDocker
- Installation-- Installation ofDocker
- Using Docker-- UsingDocker
- Ansible and Docker-- Using Ansible to manageDocker
- Building Docker Images using Ansible-- Using Ansible to buildDockerimages
Building Docker Images with Ansible using a Dockerfile
Michael's articledetails how to install Ansible, how to usePaul Durivage'sangstwad.dcoker_ubuntu Ansible role, also features an important-to-know way of building Docker images whereby an image is build using a Dockerfile that specifies the installation ofAnsible, checks out your playbook repository which it then runs with Ansible resulting in a built image with everything you would want on that image. This is different than in the previous post that details using Ansible to run theDockerimage-building process and is yet another example on how usingAnsibleandDockertogether is flexible and the approach to both interchangeable and each method equally valid depending on what the user requires.
Additionally, I used this methodology when I first started usingAnsibleandDockerand forked Michael's repository, adding aGalera role.
The Playbook
In addition to showing yet another way to buildDockerimages, this post will also give the reader more insight into usingAnsiblein general and show another example of what one can do with aDockerfile.
This post will detail a playbook I wrote when I forked thedocker_dna repo. In my role with the HP ATG Group, I was tasked with researching Ansible and Docker and wanted to accomplish several things: Learn Docker and Ansible as well as see if my experience -- and a [Salt][saltstack] template and methodology for setting up a Galera cluster could be easily ported toAnsible.
Directory layout
The repo, when cloned, there are thebase
,rabbitmq
,zookeeper
, andgalera
subdirectories. The last one was added by myself when I used this repo to get familiar with this methodology for buildingDockerimages. In that subdirectory
<code data-lang="text">$ ls -1dna.ymldocker-dna_galera.ymlDockerfilegroup_varshost_varsREADME.mdroles</code>
Top-level playbook
Thedna.yml
playbook sets some variables and includesdocker-dns_galera.yml
:
<code data-lang="text">---# file: dna.yml- include: docker-dna_galera.yml</code>
Tasks
The tasks that then are used for this role which are broken up into specific operations:
<code data-lang="text">$ ls -1 roles/docker-dna_galera/tasks/clustercheck.ymlconfigure_galera.ymlgrants.ymlinstall_galera.ymlmain.ymlmisc.ymlrepo.yml</code>
Specifying using thedocker-dna_galera
role
docker-dna_galera.yml
in turn uses the rolescommon
anddocker-dns_galera
<code data-lang="text">---# file: docker-dna_galera.yml- hosts: docker-dna_galeraroles:- common- docker-dna_galera</code>
Role variables
By using thedocker-dns_galera
role, the role's variables are set in the fileroles/docker-dna_galera/vars/main.yml
which contains variables used by the the templatesroles/docker-dna_galera/templates/etc/mysql/my.cnf.j2
androles/docker-dna_galera/templates/usr/bin/clustercheck.j2
, as well as some of the role's tasks.
<code data-lang="text">---# file: roles/docker-dna_galera/vars/main.yml# these values are default - change for security!galera: dbusers: xtrabackup: username: xtrabackup password: xtrabackup docker: username: docker password: docker host: 172.17.% clustercheck: username: clustercheck password: clustercheck</code>
Top-level playbook including tasks
main.yml
includes each task in the order it needs to be run:
<code data-lang="text">--# file: roles/docker-dna_percona/tasks/main.yml- include: misc.yml- include: repo.yml- include: install_galera.yml- include: grants.yml- include: configure_galera.yml- include: clustercheck.yml</code>
Misc playbook
The first taskmisc.yml
installs vim or any other package other than thePerconapackages:
<code data-lang="text">---# file: roles/docker-dna_percona/tasks/misc.yml- name: Install things I likeapt: pkg= state=presentwith_items:- vim</code>
Set the repo
Therepo.yml
task simply sets up apt to use thePerconaapt repo:
<code data-lang="text">---# file: roles/docker-dna_galera/tasks/repo.yml- name: Obtain Percona public key# apt_key: url=http://keys.gnupg.net/pks/lookup?op=get&search=0x1C4CBDCDCD2EFD2Aapt_key: url=http://www.percona.com/downloads/RPM-GPG-KEY-percona state=present- name: Add Percona repositoryapt_repository: repo='deb http://repo.percona.com/apt precise main'state=present- name: Add Percona source repositoryapt_repository: repo='deb-src http://repo.percona.com/apt precise main'state=present- name: Update apt cacheapt: update_cache=yes</code>
Install the database software
Theinstall_galera.yml
task installsPercona XtraDB Clusteras well as copying a startup script into /usr/local/bin. This is somewhat historic as upstart didn't work with older versions ofDocker
<code data-lang="text">---- name: Install Percona XtraDB Cluster serverapt: pkg= state=presentwith_items:- percona-xtradb-cluster-server-5.6- python-mysqldb- xinetd- telnet- name: Copy the helper scriptcopy: src=usr/local/bin/mysql_run.shdest=/usr/local/bin/mysql_run.shmode=0755</code>
Set the database grants
Thegrants.yml
task sets the grants for the database that are needed to run a successful Galera cluster
<code data-lang="text">---# file: roles/docker-dna_percona/tasks/grants.yml- name: Add Docker database usermysql_user: user= host=password= priv=*.*:"all privileges"- name: Add xtrabackup database user (for Galera SST)mysql_user: user= host="localhost" password= priv=*.*:"grant, reload, replication client"- name: Add clustercheck database user (for clustercheck/xinetd -> haproxy)mysql_user: user= host="localhost" password= priv=*.*:"grant, reload, replication client"</code>
Configure the database
configure_galera.yml
generates/etc/mysql/my.cnf
and shuts down themysqld
process. Why shut it down? Because the container this is running on is only for building the image and just as when creating a snapshot, it makes more sense to not have a running database with open file-handles that an image is created from.
<code data-lang="text">---# file: roles/docker-dna_percona/tasks/configure_galera.yml- name: Configure Percona XtraDB Cluster servertemplate: src=etc/mysql/my.cnf.j2dest=/etc/mysql/my.cnf- name: Stop MySQLaction: service name=mysql state=stopped</code>
Set up the clustercheck script forHAProxy
The last task,clustercheck.yml
, sets up the python script used byHAProxyto determine which master to use. Why not the original xinetd-based clustercheck script? The author was never able to get the xinetd-based clustercheck script working with Docker.
<code data-lang="text"># file: roles/docker-dna_percona/tasks/clustercheck.yml- name: Copy clustercheck scriptcopy: src=usr/local/bin/pyclustercheck dest=/usr/local/bin/pyclustercheck owner=root group=root mode=0700</code>
Template generation
The templates for thedocker-dna_percona
role are themy.cnf.j2
jinja template which is generated as/etc/mysql/my.cnf
and transliterates the variables set in the previously-mentioned variables file. This snippet shows the Galera-specific mysql options. The cluster address is set to bootstrap. Remember that this is an image that is being built. One would need to useAnsibleto configure this value to reflect node membership state of the cluster when the containers are run that use this image as well as set different passwords.
<code data-lang="text">wsrep_provider= /usr/lib/libgalera_smm.sowsrep_slave_threads = 4wsrep_sst_method= xtrabackupwsrep_sst_auth= :wsrep_cluster_name= percona-clusterwsrep_cluster_address = gcomm://wsrep_provider_options= gcache.size=2G;</code>
Dockerfile goodness
Finally, theDockerfile! This is where all the work happens.
<code data-lang="text"># docker-dna/galera/Dockerfile## VERSION0.1.0#FROM capttofu/docker-dna_baseMAINTAINER Patrick aka CaptTofu Galbraith , patg@patg.net# Update distributionRUN apt-get update / && apt-get upgrade -y / && apt-get clean# Add filesADD . ./DockerDNA# Install Percona XtraDB Cluster RUN ( echo '[docker-dna_galera]' && / echo 'localhost' /) > /etc/ansible/hosts / && ansible-playbook ./DockerDNA/dna.yml --connection=local / && apt-get clean# Expose MySQL/GaleraEXPOSE 3306 4444 4567 4568 9200ENTRYPOINT ["/usr/local/bin/mysql_run.sh"]</code>
The aboveDockerfilespecifies using thecapttofu/docker-dna_base
image as a base. This image already has ansible and it's prerequisite libraries pre-installed and ready to use. The first event that is run in the Dockerfile is to update the apt system. Next, everything in the current repository is copied to aDockerDNA
directory in the root directory of the temporary container.
Building the image
Next, by runningdocker build .
in the same directory, the image will be built, using the pre-installed ansible, run with a l;ocal connection, in this case.
<code data-lang="text">docker-dna-galera/galera$ docker build .Uploading context 49.15 kBUploading contextStep 0 : FROM capttofu/docker-dna_basePulling repository capttofu/docker-dna_base1e47da3640f1: Download complete80cd3d2446e3: Download complete5607ff993e85: Download complete27e469823903: Download complete ---> 167dc428d943Step 1 : MAINTAINER Patrick aka CaptTofu Galbraith , patg@patg.net ---> Running in ceb1ec12aab7 ---> c7916cff77cdRemoving intermediate container ceb1ec12aab7Step 2 : RUN apt-get update&& apt-get upgrade -y&& apt-get clean ---> Running in d5b1189506ecGet:1 http://security.ubuntu.com precise-security Release.gpg [198 B]Get:2 http://ppa.launchpad.net precise Release.gpg [316 B] Hit http://archive.ubuntu.com precise/main Translation-enHit http://archive.ubuntu.com precise/universe Translation-enGet:20 http://archive.ubuntu.com precise-updates/main Translation-en [431 kB]Get:21 http://archive.ubuntu.com precise-updates/universe Translation-en [180 kB]Fetched 4734 kB in 20s (228 kB/s)Reading package lists...Reading package lists...Building dependency tree...Reading state information...The following packages have been kept back:ansible initscripts upstartThe following packages will be upgraded:apt apt-utils base-files ca-certificates curl dpkg file gnupg gpgv ifupdowninitramfs-tools initramfs-tools-bin iproute libapt-inst1.4 libapt-pkg4.12libc-bin libc6 libcurl3 libcurl3-gnutls libdrm-intel1 libdrm-nouveau1alibdrm-radeon1 libdrm2 libgnutls26 libmagic1 libssl1.0.0 libudev0libyaml-0-2 multiarch-support openssh-client openssl perl-base procpspython-apt python-apt-common python-software-properties python2.7python2.7-minimal tzdata udev40 upgraded, 0 newly installed, 0 to remove and 3 not upgraded.Need to get 23.0 MB of archives.After this operation, 14.3 kB of additional disk space will be used.Get:1 http://archive.ubuntu.com/ubuntu/ precise-updates/main base-files amd64 6.5ubuntu6.7 [61.0 kB]Get:2 http://archive.ubuntu.com/ubuntu/ precise-updates/main dpkg amd64 1.16.1.2ubuntu7.5 [1829 kB]Get:40 http://archive.ubuntu.com/ubuntu/ precise-updates/main python-software-properties all 0.82.7.7 [23.5 kB]debconf: unable to initialize frontend: Dialogdebconf: (TERM is not set, so the dialog frontend is not usable.)debconf: falling back to frontend: ReadlineInstalling new version of config file /etc/issue.net ...ldconfig deferred processing now taking placeProcessing triggers for initramfs-tools ... ---> 0a8159128717Removing intermediate container d5b1189506ecStep 3 : ADD . ./DockerDNA ---> 93766d0fc5b2Removing intermediate container f4b216a8ddbfStep 4 : RUN ( echo '[docker-dna_galera]' &&echo 'localhost') > /etc/ansible/hosts&& ansible-playbook ./DockerDNA/dna.yml --connection=local&& apt-get clean ---> Running in e41cd0dba011PLAY [docker-dna_galera] ******************************************************GATHERING FACTS ***************************************************************ok: [localhost]TASK: [Install things I like] *************************************************changed: [localhost] => (item=vim)TASK: [Obtain Percona public key] *********************************************changed: [localhost]TASK: [Add Percona repository] ************************************************changed: [localhost]TASK: [Add Percona source repository] *****************************************changed: [localhost]TASK: [Update apt cache] ******************************************************ok: [localhost]TASK: [Install Percona XtraDB Cluster server] *********************************changed: [localhost] => (item=percona-xtradb-cluster-server-5.6,python-mysqldb,xinetd,telnet)TASK: [Copy the helper script] ************************************************changed: [localhost]TASK: [Add Docker database user] **********************************************changed: [localhost]TASK: [Add xtrabackup database user (for Galera SST)] *************************changed: [localhost]TASK: [Add clustercheck database user (for clustercheck/xinetd -> haproxy)] ***changed: [localhost]TASK: [Configure Percona XtraDB Cluster server] *******************************changed: [localhost]TASK: [Stop MySQL] ************************************************************ok: [localhost]TASK: [Copy clustercheck script] **********************************************changed: [localhost]TASK: [Copy clustercheck script] **********************************************changed: [localhost]</code>
Verifying image
When this has completed, the image,capttofu/docker-dna_base
, will be ready to use, in this case a container runningPercona XtraDB Clusterthat will need to be managed by Ansible in order to set up the galera cluster.
<code data-lang="text">$ docker imagesREPOSITORY TAGIMAGE IDCREATED VIRTUAL SIZE<none> <none> cba0a737d93414 hours ago850.7 MBubuntu 12.10e314931015bd13 days ago 172.2 MBubuntu quantale314931015bd13 days ago 172.2 MBubuntu 13.10145762641db913 days ago 180.2 MBubuntu saucy145762641db913 days ago 180.2 MBubuntu 14.04ad892dd21d6013 days ago 275.5 MBubuntu latest ad892dd21d6013 days ago 275.5 MBcapttofu/docker-dna_base latest 167dc428d9434 months ago350.6 MBcapttofu/docker-dna_base 0.1.01e47da3640f14 months ago798.7 MBcapttofu/docker-dna_base 12.04.w1 5150446a5dd34 months ago350.6 MB</none></none></code>
Summary
This blog post showed the reader yet another way to useDockerandAnsibletogether to build Docker images by using aDockerfileto run Ansible to install packages and configure the temporary container that is being used to build the image. This provides yet another example of the flexibility of these two great applications and gives the user yet another method in their toolbox of solutions. Another side-benefit of this article was also learning how to installPercona XtraDB ClusterwithAnsible.

데이터베이스 및 프로그래밍에서 MySQL의 위치는 매우 중요합니다. 다양한 응용 프로그램 시나리오에서 널리 사용되는 오픈 소스 관계형 데이터베이스 관리 시스템입니다. 1) MySQL은 웹, 모바일 및 엔터프라이즈 레벨 시스템을 지원하는 효율적인 데이터 저장, 조직 및 검색 기능을 제공합니다. 2) 클라이언트 서버 아키텍처를 사용하고 여러 스토리지 엔진 및 인덱스 최적화를 지원합니다. 3) 기본 사용에는 테이블 작성 및 데이터 삽입이 포함되며 고급 사용에는 다중 테이블 조인 및 복잡한 쿼리가 포함됩니다. 4) SQL 구문 오류 및 성능 문제와 같은 자주 묻는 질문은 설명 명령 및 느린 쿼리 로그를 통해 디버깅 할 수 있습니다. 5) 성능 최적화 방법에는 인덱스의 합리적인 사용, 최적화 된 쿼리 및 캐시 사용이 포함됩니다. 모범 사례에는 거래 사용 및 준비된 체계가 포함됩니다

MySQL은 소규모 및 대기업에 적합합니다. 1) 소기업은 고객 정보 저장과 같은 기본 데이터 관리에 MySQL을 사용할 수 있습니다. 2) 대기업은 MySQL을 사용하여 대규모 데이터 및 복잡한 비즈니스 로직을 처리하여 쿼리 성능 및 트랜잭션 처리를 최적화 할 수 있습니다.

InnoDB는 팬텀 읽기를 차세대 점화 메커니즘을 통해 효과적으로 방지합니다. 1) Next-Keylocking은 Row Lock과 Gap Lock을 결합하여 레코드와 간격을 잠그기 위해 새로운 레코드가 삽입되지 않도록합니다. 2) 실제 응용 분야에서 쿼리를 최적화하고 격리 수준을 조정함으로써 잠금 경쟁을 줄이고 동시성 성능을 향상시킬 수 있습니다.

MySQL은 프로그래밍 언어가 아니지만 쿼리 언어 SQL은 프로그래밍 언어의 특성을 가지고 있습니다. 1. SQL은 조건부 판단, 루프 및 가변 작업을 지원합니다. 2. 저장된 절차, 트리거 및 기능을 통해 사용자는 데이터베이스에서 복잡한 논리 작업을 수행 할 수 있습니다.

MySQL은 오픈 소스 관계형 데이터베이스 관리 시스템으로, 주로 데이터를 신속하고 안정적으로 저장하고 검색하는 데 사용됩니다. 작업 원칙에는 클라이언트 요청, 쿼리 해상도, 쿼리 실행 및 반환 결과가 포함됩니다. 사용의 예로는 테이블 작성, 데이터 삽입 및 쿼리 및 조인 작업과 같은 고급 기능이 포함됩니다. 일반적인 오류에는 SQL 구문, 데이터 유형 및 권한이 포함되며 최적화 제안에는 인덱스 사용, 최적화 된 쿼리 및 테이블 분할이 포함됩니다.

MySQL은 데이터 저장, 관리, 쿼리 및 보안에 적합한 오픈 소스 관계형 데이터베이스 관리 시스템입니다. 1. 다양한 운영 체제를 지원하며 웹 응용 프로그램 및 기타 필드에서 널리 사용됩니다. 2. 클라이언트-서버 아키텍처 및 다양한 스토리지 엔진을 통해 MySQL은 데이터를 효율적으로 처리합니다. 3. 기본 사용에는 데이터베이스 및 테이블 작성, 데이터 삽입, 쿼리 및 업데이트가 포함됩니다. 4. 고급 사용에는 복잡한 쿼리 및 저장 프로 시저가 포함됩니다. 5. 설명 진술을 통해 일반적인 오류를 디버깅 할 수 있습니다. 6. 성능 최적화에는 인덱스의 합리적인 사용 및 최적화 된 쿼리 문이 포함됩니다.

MySQL은 성능, 신뢰성, 사용 편의성 및 커뮤니티 지원을 위해 선택됩니다. 1.MYSQL은 효율적인 데이터 저장 및 검색 기능을 제공하여 여러 데이터 유형 및 고급 쿼리 작업을 지원합니다. 2. 고객-서버 아키텍처 및 다중 스토리지 엔진을 채택하여 트랜잭션 및 쿼리 최적화를 지원합니다. 3. 사용하기 쉽고 다양한 운영 체제 및 프로그래밍 언어를 지원합니다. 4. 강력한 지역 사회 지원을 받고 풍부한 자원과 솔루션을 제공합니다.

InnoDB의 잠금 장치에는 공유 잠금 장치, 독점 잠금, 의도 잠금 장치, 레코드 잠금, 갭 잠금 및 다음 키 잠금 장치가 포함됩니다. 1. 공유 잠금을 사용하면 다른 트랜잭션을 읽지 않고 트랜잭션이 데이터를 읽을 수 있습니다. 2. 독점 잠금은 다른 트랜잭션이 데이터를 읽고 수정하는 것을 방지합니다. 3. 의도 잠금은 잠금 효율을 최적화합니다. 4. 레코드 잠금 잠금 인덱스 레코드. 5. 갭 잠금 잠금 장치 색인 기록 간격. 6. 다음 키 잠금은 데이터 일관성을 보장하기 위해 레코드 잠금과 갭 잠금의 조합입니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

WebStorm Mac 버전
유용한 JavaScript 개발 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.
