CoreOS Practice Guide (eight): Unit file Details

Source: Internet
Author: User
Keywords Docker coreos unit file
Tags access advanced apache application available for based clear cloud

Note: This article starts in CSDN, reprint please indicate the source.

"Editor's note" in the previous articles in the "Walking Cloud: CoreOS Practice Guide" series, ThoughtWorks's software engineer Linfan introduced CoreOS and its associated components and usage, which mentioned how to configure Systemd Managed system services using the unit file. This article will explain in detail the specific format of the unit file and the available parameters.


Author Introduction:

Linfan, born in the tail of the IT siege Lions, thoughtworks Chengdu Office Cloudops team members, usually like in the spare time to study DevOps related applications, currently in preparation for AWS certification and promotion of Docker related technologies.

After the new year, first of all thank you for chasing CoreOS series of readers, I wish you a bosom friend, the year of the Sheep luck!

In the previous section of the series, we have covered the way in which system services are configured SYSTEMD managed using the unit file, and the CoreOS Fleet tool inherits and extends this file format, making it more applicable to the service configuration of the clustered environment. Since the unit file itself is all-inclusive and is of relative advanced content, in the previous sections of the series, there is no detailed explanation of the specific format and parameters available for the system. In fact, this part of the knowledge is the way to CoreOS System Management master. Now it's time to go deep.

This part of the content is not very independent, the need for readers to SYSTEMD and fleet have a certain understanding, if you have not read the contents of these two parts, it is necessary to return to review.

systemd Unit File

In the SYSTEMD biosphere (in addition to CoreOS, the current mainstream Linux systems, such as Arch, SUSE, Fedora, Redhat/centos have also been used systemd, in addition to Ubuntu will be the fastest version of 15.04 to enable SYSTEMD as the default System Management tool, the unit file unifies the various system resource configuration formats in the past, such as service start/stop, timing tasks, device mount, network configuration, device configuration, virtual memory configuration, and so on. and systemd through different file suffix names to differentiate these profiles, before we wrote the. service file is one of them. The following are 12 types of unit files supported by SYSTEMD.

Suffix name

Role

. automount

Used to control the automatic mounting of file systems. Automatic mount that is, when a directory is accessed, the system automatically mounts the directory, which replaces the traditional Linux system autofs corresponding functions

. device

corresponding to/dev directory equipment, mainly used to define the dependencies between devices

. Mount

Defines a mount point in the hierarchy of the system structure that replaces the previous Fstab configuration file

. path

Used to monitor the specified directory changes and trigger other unit runs

. Scope

This type of unit file is not created by the user, but is generated by the SYSTEMD runtime, describing the grouping information for some system services

. Service

Encapsulation daemon startup, stop, restart, and overload operations are the most common type of unit

. Slice

Some of the information used to describe cgroup is rarely used, and the average user ignores it.

. snapshot

This unit is actually a snapshot of the Systemctl Snapshot command created to describe the SYSTEMD unit run state

. socket

The socket message in the monitoring system or the Internet, which can be used to automatically trigger service launch based on network data

. Swap

Define a swap partition for virtual memory

. Target

Used to logically group the Unit to guide the execution of other unit. It replaces the operational level in SYSV and provides a more flexible way to boot based on specific device events. For example, Multi-user.target is equivalent to a previous run level of 5, and Bluetooth.target is triggered when a Bluetooth device is plugged in

. timer

Encapsulates the action of time triggered by the inside of system, replacing the crontab function

these dazzling variety, almost encompassing the most of the day-to-day work of system management, consistent configuration format and operation methods so that even ordinary Linux users and software developers can quickly start to modify the configuration of the system, MOM no longer have to worry about us to hang the system. In fact, not many of these profile types actually need to be modified, and this article is intended to be the most commonly used, as it has been written before. Service type expand description. Mainly for the sake of space, however, since the format is unified, as long as a configuration type is cooked, the other configuration learning is not minutes:D


Again, the unit file should be placed in one of the specified 3 system directories according to the SYSTEMD convention. These 3 directories are prioritized and, according to the table below, the higher the precedence, so that when there are files of the same name in several directories, only the one in the highest priority directory is used.

Path

Description

/etc/systemd/system

System or user supplied configuration file

/run/systemd/system

Configuration files generated by software runtime

/usr/lib/systemd/system

Configuration files added during system or Third-party software installation

Since the last directory here is a read-only partition of the system in CoreOS, in CoreOS, third party software may need to be specially processed when it is installed to place the configured unit files in the/run/systemd/system directory. Simply CoreOS was not recommended to install software directly on the system, people deliberately to make the system partition to read this meaning has been very clear. Some software that does need to be installed on CoreOS such as Deis, it's. Service provisioning is in the/run/systemd/system directory.


Service File

Come straight to the point and take a look at two actual service profiles.

The first configuration is the unit file for the Docker service in the CoreOS system, the path is/usr/lib/systemd/system/docker.service, and you can see that the content is fairly compact and readable.

[Unit]


Description=docker creator Container Engine


documentation=http://docs.docker.com


after=docker.socket early-docker.target network.target


Requires=docker.socket Early-docker.target


[Service]


environment=tmpdir=/var/tmp


environment=docker_opts= '--insecure-registry= ' 0.0.0.0/0 '


environmentfile=-/run/docker_opts.env


limitnofile=1048576


limitnproc=1048576


Execstart=/usr/lib/coreos/dockerd--daemon--host=fd://$DOCKER _opts


[Install]


Wantedby=multi-user.target

The second configuration has a different style than the previous one, but the same content is clear and clear. This configuration comes from a document in CoreOS that launches an Apache service container and registers the service's running information into ETCD.

(Note that there seems to be an error in the example in the original text of this document that when Docker is started, the command argument in Execstart-P 80:80 should be-P 8,081:80, the following code has been amended)

[Unit]


description=my Advanced Service


After=etcd.service


After=docker.service


[Service]


timeoutstartsec=0


Execstartpre=-/usr/bin/docker Kill Apache1


Execstartpre=-/usr/bin/docker RM apache1


Execstartpre=/usr/bin/docker Pull Coreos/apache


Execstart=/usr/bin/docker Run--name apache1-p 8081:80coreos/apache/usr/sbin/apache2ctl-d FOREGROUND


Execstartpost=/usr/bin/etcdctl set/domains/example.com/10.10.10.123:8081 Running


Execstop=/usr/bin/docker Stop Apache1


Execstoppost=/usr/bin/etcdctl rm/domains/example.com/10.10.10.123:8081


[Install]


Wantedby=multi-user.target

Carefully observed two service configurations, some of which have obvious common ground. We then take these two unit files as an example, step-by-step analysis of the SYSTEMD service configuration.

The service's unit file can be divided into 3 configuration sections, where the unit and Install segments are common to all the unit files to configure the description, dependencies, and system startup of the service (or other system resources). The service segment is specific to the unit file (suffix. Service) of the services type, which defines how the service is managed and manipulated. Each of the other configuration files will also have a unique configuration segment, which is the most obvious difference between several different unit profiles.

See what parameters are commonly used in each configuration segment.

Unit Segment

Description

A paragraph describing the unit file is usually a short sentence.

Documentation

Specifies the document for the service, which can be the URL path for one or more documents.

Requires

A list of other unit dependencies that are listed in, which is also started at the same time that the service is started, and if any of the services fail to start, the service is terminated.

wants

Similar to Requires, but only when this unit is configured to start, triggers the launch of each unit module listed, regardless of whether the modules started successfully.

after

Similar to Requires, but will not start the current service until all of the modules listed later start complete.

Unreported

In contrast, before you start any of the specified modules, you first ensure that the current service is already running.

Bindsto

Similar to Requires, but a stronger association. When this service is started, all of the listed modules are started at the same time, terminating the current service when a module fails to start. Conversely, the current service is automatically started as long as all listed modules are started. And any one of these modules is accidentally terminated or restarted, and the service terminates or reboots.

partof

This is a subset of the BindTo function that terminates or restarts the current service only if any of the listed modules fail or restart without starting the list module.

onfailure

When this module fails to start, each module listed is automatically started.

Conflicts

A module that conflicts with this module, if the list is already running in the module, the service will not start, and vice versa.

These configurations, except description, can be added multiple times. For example, the after parameter in the first example is used to specify all the values in a single line, or you can use multiple after arguments as in the second example to specify a value in each row of arguments.

II, Install Duan

The configuration in this section is similar to the unit, but this part of the configuration needs to be activated through the Systemctl enable command and can be disabled through the systemctl disable command. In addition, this part of the configured target module is usually a. target file at a specific boot level, which is used to enable the service to run automatically when the system starts.

Wantedby

Similar to the previous wants, it is not the modules that the service relies on, but the modules that rely on the current service.

Requiredby

Similar to the previous requires, the following list is not the module that the service relies on, but the module that relies on the current service.

Also

When this service is enable/disable, each module listed later is automatically enable/disable.

The two examples above use "wantedby=multi-user.target" to indicate that the service needs to be run automatically when the system is started in multi-user mode (the default run level). Of course, the Systemctl enable activation of this service will not take effect until it is automatically run. See this article for the running level of Linux system startup.

three, Service section

This section is unique to the. service file and is the most important part of the service configuration. This section of the configuration options are very many, mainly divided into service lifecycle Control and service context configuration two aspects, the following is a more commonly used parameters.

Service lifecycle Control-related parameters:

Type

Type of service, commonly used with simple (default type) and forking. The default simple type can be adapted to most scenarios, so you can generally ignore the configuration of this parameter. And if the service program starts by fork system calls to create the child process and then closes the application itself, the value of the type should be set to forking, or the SYSTEMD will not track the behavior of the subprocess, and the service is considered exited.

Remainafterexit

The value is True or false (yes or no), and the default is False. When the configuration value is true, SYSTEMD will only be responsible for starting the service process, and SYSTEMD will still consider the service to be running even if the service process exits. This configuration is primarily provided to some not resident memory, but rather a special type of service that exits immediately after registering and waits for messages to be started on demand

Execstart

This parameter is available for almost every. service file, specifying the primary command to start the service, which can only be used once per configuration file.

Execstartpre

Specifies that before starting the command to execute Execstart, there can be multiple, as shown in the previous second example, all commands are executed in the order in which they are written in the file.

Execstartpost

Specifies that the closure of the command after the execution of the Execstart is started, or there can be multiple.

timeoutstartsec

The number of seconds to wait for the service to start, and SYSTEMD will assume that the service fails automatically if the service does not perform all of the startup commands after this time. This configuration is very important to use the Docker container hosted application, because the first time the Docker can be able to download the service from the network mirror files, resulting in a more serious delay, easy to be systemd misjudged as a start failure and kill. Typically for this service, you need to specify the value of Timeoutstartsec as 0 to turn off timeout detection, as in the second example above.

Execstop

The primary command required to stop the service.

Execstoppost

Specifies that the end of the Execstop command is done, or that there can be multiple.

timeoutstopsec

The number of seconds to wait for the service to stop, and if the service does not stop at this time, SYSTEMD will use the SIGKILL signal to forcibly kill the service process.

Restart

This value is used to specify under what circumstances the service process needs to be restarted. Commonly used values are no,on-success,on-failure,on-abnormal,on-abort and synch. The default value is no, that is, the service is not automatically restarted. These different values indicate under what circumstances the service will be restarted, as shown in the following table.

Service Exit Reason

No

Synch

On-failure

On-abnormal

On-abort

No-success

Normal exit

Exception exit

Start/Stop Timeout

Abnormal kill




restartsec

If the service needs to be restarted, the value of this parameter is the number of seconds to wait before the service is restarted.

Execreload

The primary command required to reload the service.

Service context Configuration Related parameters:

Environnement

Add environment variables to the service, as shown in the first example above.

Environmentfile

Specifies that a file containing a list of environment variables required by the service is loaded, and each row in the file is defined as an environment variable.

Nice

The process priority of the service, the smaller the value the higher the priority, the default is 0. 20 is the highest priority and 19 is the lowest priority.

WorkingDirectory

Specifies the working directory for the service.

rootdirectory

Specifies the root directory (/directory) of the service process, and if this parameter is configured, the service will not be able to access any files other than the specified directory.

User

Specifies that the user who is running the service affects the service's access to the local file system.

Group

Specifying the group of users running the service affects the service's access to the local file system.

Limitcpu/limitstack/limitnofile/limitnproc and other

Limit the amount of system resources available to a particular service, such as the CPU, the program stack, the number of file handles, the number of child processes ... Instead of expanding the description, the value can refer to those parameters that begin with the Rlimit_ in the Linux document resource Quota section.

Column so a big push parameter I am also drunk (these are commonly used parameters, not commonly used to write), but in fact, the essence of systemd is here. After careful deliberation, there are still some rules between the lengthy parameters, and most of them can be literally, so the task of writing unit files is not boring. In the past, we need to learn n different configuration formats to manage n different system resources, SYSTEMD's concept is really advanced too much. And these parameters, and so on, probably only use a lot more, will think they look less annoying O (//_//) o

X-fleet segment

of

Fleet

The unit files used by SYSTEMD are discussed earlier. In the Fleet of this series, the service configuration in Fleet is demonstrated.

Fleet's Unit service description file is actually a copy of the SYSTEMD. Service profile. However, in order to facilitate the adaptive management of the service in the cluster environment, Fleet adds a x-fleet segment based on the SYSTEMD's unit configuration, which is specifically designed to describe which nodes the service should be assigned to the cluster to start. It has only 5 available parameters, please come out and make a debut.

MachineID

To tell fleet that this service can only run on a particular node, note that the value here must be a full node ID, which can be obtained by the "fleetctllist-machines-l" command.

machineof

Value is another. service file that indicates that the current service must be running on the same node as the specified service.

Machinemetadata

A value is the metadata content of a node, such as "region=us-east-1". These Metadata are written through Cloudinit when the node is started, as mentioned in the fleet of the series. This parameter can be used multiple times, or multiple values are passed in at the same time by a space divider.

Conflicts

Value is a. service file, the conflicts parameter can also be used multiple times, and its value can use wildcard characters, such as apache* to represent all services that start with "Apache".

Global

If the value is true, the service is deployed to each node in the cluster that meets the Machinemetadata qualification. Note that when the Global value is true, all other constraints except machinemetadata are ignored.

The first four parameters are named X-conditionmachineid, X-conditionmachineof, X-conditionmachinemetadata, and X-conflicts before the fleet v0.8 version. These are now discontinued, but may still appear in some of the earlier documents or web articles, and if you see them, float away. Unit template

In reality, there are often applications that need to be replicated in multiple runs, such as multiple instances of the same service running after a load-balancing instance. But according to the previous example, each service needs a separate unit file, so copying multiple copies of the same file is obviously not convenient for service management. For this systemd defines a special Service unit file, called the unit template.

The main feature of the

template file is that the filename ends with the @ sign, and the unit name specified when it is started is called the template name appended with a parameter string. For example, modify the second unit file in the previous example to a template that can be used to start multiple instances. First, modify the file name, add an @ symbol such as the original filename is Apache.service, then you can modify it to apache@.service, the purpose is to surface the file is a template file. When a service starts, you can place an additional string parameter that distinguishes the service instance, usually using the listener port number or the console TTY number used. For example, "Systemctl start Apache@8080.service". Second, then modify the unit file content

The unit file can get additional parameters when the service is started, so it is often necessary to modify the parts that should not be fixed in the server file, such as the IP and port on which the service listens, and replace it with an additional parameter.

[Unit]


description=my Advanced Service Template


After=etcd.servicedocker.service


[Service]


timeoutstartsec=0


Execstartpre=-/usr/bin/docker Kill apache%i


Execstartpre=-/usr/bin/docker RM apache%i


Execstartpre=/usr/bin/docker Pull Coreos/apache


Execstart=/usr/bin/docker Run--name apache%i-p%i:80coreos/apache/usr/sbin/apache2ctl-d FOREGROUND


Execstartpost=/usr/bin/etcdctl set/domains/example.com/%h:%i Running


Execstop=/usr/bin/docker Stop Apache1


Execstoppost=/usr/bin/etcdctl rm/domains/example.com/%h:%i


[Install]


Wantedby=multi-user.target

Take a closer look at the changes and use the placeholder%h and%i, where there are 6 types of placeholders (19 of them, less frequently used documents) that are dynamically replaced by the actual values at unit startup.

Placeholder

Role

%n

Complete unit file name, including. Service suffix name

People%m

The Machine ID of the actual running node, suitable for use as part of the ETCD path, such as/machines/%m/units

%b

function is a bit like Machine ID, but this value changes each node reboot, called the Boot ID

%H

Host name of the actual running node

%p

The part of the unit file name before the @ symbol, excluding the @ symbol

%i

The part of the unit file name that follows the @ symbol, excluding the @ symbol and the. Service suffix name

Incidentally, these parameters, in addition to%i, can also be used in a unit file that is not a template. %p is dynamically replaced in the normal unit file with the service name removed. The name of the services suffix.

Third, start the Unit template service instance

The startup of the template service is roughly the same for Systemd and Fleet.

SYSTEMD is slightly simpler and requires only the runtime plus the suffix parameter. For example, "Systemctl start Apache@8080.service". SYSTEMD first looks for a file named Apache@8080.service in its specific directory, and if it is not found, and the file name contains the @ character, it tries to remove the suffix parameter matching template file. For example, if Apache@8080.service is not found, then Systemd finds Apache@.service and instantiates it through the template file.

Fleet does not have a specific unit file storage directory, but adds the suffix parameter when specifying the unit file path through the Fleetctl start or fleetctl submit command, Fleet automatically matches the template file after the suffix parameter is removed. For example, "Fleetctl submit ${home}/apache@8080.service" matches the Apache@.service template file below the ${home} directory.

in the following synthesis case, the actual example will also be used to describe the template usage scenes in detail. Summary

The content of this article is slightly fragmentary, it is mainly to the system resources and services in the CoreOS play a role in the management of the unit configuration file is more in-depth description. In particular, the final unit template partly gives the service the ability to expand horizontally, and is used fairly widely in the actual project environment. These systems management skills, the need for a certain degree of practical training to realize the benefits.

Recently, some colleagues asked me, introduced so many CoreOS, can use a sentence to comment on the system, and it is most suitable for what kind of application scenarios?

For the first question, CoreOS is not a mysterious silver bullet, it's just a "more advanced concept (see series one)" and "friendly to the cluster and application containers," the server Linux distribution. Some people will ask, if the CoreOS and other distributions to compare which useful. This one... The focus of the field is different Ah, CoreOS will never replace Fedora and Ubuntu desktop Linux distribution, because it is a highly streamlined operating system without GUI and X-window (but not that CoreOS can not provide the services that need GUI) Because the X-window and VNC services can be installed in the container.

There is no exact answer to the second question, and the choice of Linux system distributions is entirely a matter of personal preference. In general, automated seamless upgrades based on CoreOS and features for container and cluster friendliness are more applicable to clusters that require long-term operation and have a scale-out architecture, especially a micro service architecture, for external delivery purposes. But not that CoreOS can not be used in the general server scenario, the United States SaaS Cloud Services Web site Iron.io and shopping site Shopify are using CoreOS as their business support platform, their business scenarios in addition to the use of large-scale clusters, all aspects are very different.

In the next two articles will continue to introduce two integrated CoreOS of the built-in features to achieve high availability of a comprehensive case, please look forward to. (Author/linfan Zebian/Zhou Xiaolu)

Series Links:

Walking in the Clouds: CoreOS Practice Guide (i)

CoreOS Practice Guide (ii): Erection of CoreOS clusters

CoreOS Practice Guide (III): System service Housekeeper SYSTEMD

CoreOS Practice Guide (iv): Cluster command post Fleet

CoreOS Practice Guide (v): Distributed data storage ETCD (i)

CoreOS Practice Guide (vi): Distributed data storage ETCD (next)

CoreOS Practice Guide (vii): Docker Container Management Services

If you need more information about Docker or technical documentation to access the Docker technology community, if you have more questions, please put it in the Dcoker Technical Forum and we will invite experts to answer. CSDN Docker Technology Exchange QQ Group: 303806405.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.