How to create and manage services in CentOS 7 with systemd

Systemd is a system and service manager and like most major Linux distributions the init deamon was replaced by systemd in CentOS 7. One of the main functions of systemd is to manage the services, devices, mount points, sockets and other entities in a Linux system. Each of these entity that are managed by systemd is called a unit. Each unit is defined by a unit file (configuration file) which is located in one of the following directories.
DirectoryDescription
/usr/lib/systemd/system/Unit files distributed with installed packages. Do not modify unit files in this location.
/run/systemd/system/Unit files that are dynamically created at runtime. Changes in this directory are lost when rebooted.
/etc/systemd/system/Unit files created by systemctl enable and custome unit files created by system administrators.

Any custom unit files that you create should be placed in the /etc/system/system/ directory. This directory takes precedence over other directories.

Unit files names are of the form

unit_name.unit_type

Unit_type can be one of the following:

Unit TypeDescription
deviceA device unit.
serviceA system service.
socketA socket for inter-process communication.
swapA swap file or device.
targetA group of units.
timerA systemd timer.
snapshotA snapshot of systemd manager.
mountA mount point.
sliceA group of unit that manage the system processes.
pathA file or directory.
automountA automount point.
scopeAn externally created process.

Creating a new service (systemd unit)

To create a custom service to be managed by systemd, you create a unit file that defines the configuration of that service. To create a service named MyService for example, you create a file named MyService.service in /etc/systemd/system/

# vim /etc/systemd/system/MyService.service

The unit file of service consists of a set of directives that are organized in to three sections – UnitService and Install. Below is an example of a very simple unit file.

[Unit]
 Description=Service description

[Service]	
 ExecStart=path_to_executable

[Install]
 WantedBy=default.target

Once you have created the unit file with all the necessary configuration options, save the file and set the correct file permissions.

# chmod 664 /etc/systemd/system/MyService.service

The next step is to reload all unit files to make systemd know about the new service.

# systemctl daemon-reload

Finally to start the service, run

# systemctl start MyService.service

[Unit] Section

The following are the main directives that you specify in the [Unit] section.

DescriptionA short description of the unit.
DocumentationA list of URIs pointing to the documentation for the unit.
RequiresA list of units that must be started alongside the current unit. If the any these units fail to start then current unit will not be activated.
WantsSimilar to the Requires directive but the difference is the current unit will be activated even if the depended units fail to start.
BeforeList of units that cannot be started before the current unit.
AfterThe current unit can started only after the units listed here.
ConflictsList units that cannot be run concurrently with the current unit.

[Service] Section

Some of the common directives that you’ll see in service section are.

TypeDefines the startup type of the unit which can be one of the values:

  • Simple: This is the default. The main process of the service is the process started with ExecStart.
  • Forking: The process started with ExecStart spawns a new child process which becomes the main process and the parent process is terminated when the startup is completed.
  • Onehot: Similar to simple but systemd waits for the process to exit before proceeding with other units.
  • Dbus: Similar to simple but systemd waits for the process to take a name on the dbus.
  • Notify: Similar to simple Systemd will wait for a notification from the process before continuing with other units.
  • Idle: Similar to simple but service will not run until all other jobs are finished.
ExecStartSpecifies the command to the executed to start service.
ExecStartPreSpecifies the command to be executed before the main process specified in the ExecStart is started.
ExecStartPostSpecifies the command to be executed after the main process specified in the ExecStart has finished.
ExecStopSpecifies the command to be executed when the service is stopped.
ExecReloadSpecifies the command to be executed when the service is restarted.
RestartSpecifies when to restart the service automatically. Possible values are “always”, “on-success”, “on-failure”, “on-abnormal”, “on-abort”, or “on-watchdog”.

[Install] Section

The [install] section provides information required to enable or disable the units using the systemctl command. The common options are:

RequiredByA list of units that requires unit. A symbolic link of this unit is created in the .requires directory of the listed unit.
WantedBySpecifies a list of targets under which the service should be started. A symbolic link of this unit is created in the .wants directory of the listed target.

Using systemctl to manage services

systemctl is the command line tool you can use to control and manage services in systemd. Let’s now take a look at the some of the important systemctl commands for service management.

Listing Service Units and Unit files

To list all the units that are loaded

# systemctl list-units

To list only units of type service

# systemctl list-units -t service

To list all installed unit files of type service

# systemctl list-unit-files -t service

To list all installed unit files of type service

# systemctl list-unit-files -t service

You can use the --state option to filter the output by the state of the unit. The following command lists all services that are enabled.

# systemctl list-unit-files --state enabled

Note the difference between list-units and list-unit-files is that list-unit will only show units that are loaded while list-unit-files shows all unit files that are installed on the system.

Start and Stop service

This is quite straightforward, start option to start a service and stop option to stop a service

# systemctl start service_name.service
# systemctl stop service_name.service

Restart and Reload services

The restart option will restart a service that is running. If the service is not running, it will be started.

# systemctl restart service_name.service

If you want to restart the service only if its running then use the try-restart option.

# systemctl try-restart service_name.service

The reload option will try to reload the service specific configuration of a unit if it is supported.

# systemctl reload service_name.service

Enable and Disable services

Units can be enabled or disabled using the enable or disable options of systemctl command. When a unit a enabled symbolic links are created in various locations as specified in the [install] section of the unit file. Disabling a unit will remove the symbolic links that wer created when the unit was enabled.

# systemctl enable service_name.service
# systemctl disable service_name.service

Reload Unit Files

Whenever you make any changes to the unit files you need to let systemd know by executing daemon-reload which reloads all unit files.

# systemctl daemon-reload

Modifying system services

The unit files that come with installed packages are stored in /usr/lib/systemd/system/. The unit files in this directory should not be modified directly as the changes will be lost when if you update the package. The recommended method is to first copy the unit file to /etc/systemd/system/ and make the changes in that location. The unit files in /etc/systemd/system/ takes precedence over unit files in /usr/lib/systemd/system/ so the original unit file will be overridden.

Virtual Box – Different network connection

VirtualBox permette la connessione di una macchina virtuale a diversi tipi di rete locale. Vediamo nel dettaglio quali sono.

Le macchine virtuali sono fatte per collegarsi a differenti tipi di connessione LAN. In genere, in ambito domestico o delle piccole e medie imprese, vengono utilizzate solo per andare su Internet o far parte della rete locale. Per gli smanettoni o i tecnici, invece, può essere necessario creare una rete virtuale interna per effettuare esperimenti con i protocolli e le impostazioni. Insomma, c’è molta versatilità su questo aspetto. Ecco perché VirtualBox, offre diversi tipi di rete:

Network Address Translation (NAT)

Rete con NAT

Il servizio NAT è incluso in tutti i router/modem. Non fa altro che prendere tutte le connessioni dai vari computer e farle passare per una connessione unica, con un unico indirizzo IP. Perciò puoi avere una o più macchine virtuali che navigano su internet senza vedersi tra loro (ognuna di esse è in una rete isolata). In VirtualBox è la modalità predefinita e funziona con l’assegnazione di un DHCP al sistema operativo Guest.

Rete con NAT

Permette la creazione di una rete tra macchine virtuali, ma sempre con tecnologia NAT.

Bridged Networking (Scheda con bridge)

Rete con Bridge

Bridge in italiano si traduce letteralmente come “ponte”. VirtualBox fa, quindi, semplicemente da ponte tra la macchina virtuale e la rete locale. Dunque, la macchina Guest sarà collegata alla rete come qualsiasi altro computer fisico e potrà interfacciarsi con gli altri dispositivi in rete senza problemi. Ovviamente, dovrà essere configurato come un dispositivo fisico in rete (indirizzi IP, DNS, etc).

Rete Interna

Rete interna

VirtualBox permette di creare una rete interna, privata e non visibile dall’esterno. Ciò permette di avere dei server di prova con servizi come il DHCP, Active Directory, DNS, etc. Questa funzionalità garantisce il dialogo tra le macchine virtuali anche se l’Host non è collegato a nessuna rete. Infatti, le VM non possono dialogare tra loro in bridged se non c’è collegamento ad una vera rete. La “intnet”, invece, funziona sempre. Ovviamente in questo caso bisogna autoassegnarsi degli indirizzi o utilizzare un Server DHCP.

Host-only network (Scheda solo host)

Rete Host-Only

La rete di soli host è una rete interna in cui tutte le VM sono collegate tra loro (proprio come nella intnet), ma anche l’host è collegato ad essa. In questo caso vi è un’assegnazione di indirizzi IP data in automatico da VirtualBox stesso.

Il port forwarding

Port Forwarding

L’opzione NAT, come abbiamo già visto, permette ad una macchina virtuale di funzionare proprio come un computer connesso ad un router che esce su Internet. Se, però, volessimo inoltrare dei pacchetti ad una porta è possibile farlo. Un po’ come quando si aprono le porte sul router (ad esempio la 80) e si può accedere al server web tramite l’Indirizzo IP pubblico. Solo che, in questo caso, accedendo all’indirizzo host (ad es. 192.168.1.100:80) avremo un forwarding alla porta 80 della macchina virtuale.

Regole di inoltro delle porte

Managing The Postfix Queue

In this article, I will go over the tools Postfix offers you to manage the mail queue. There are 6 actions you can perform on messages in the queue.

  • List messages.
  • Delete messages.
  • Hold messages.
  • Re-queue messages.
  • Display the contents of messages.
  • Flush the messages in the queue.

Listing Messages in the Postfix Queue

Postfix provides a tool called postqueue. The command provided with the -p switch will display an entry for each message in the queue. The output will include a column for the message IDsizearrival timesend, and recipient addresses.

Messages that are currently in the active queue will display a asterisk to the right of the message ID.

If there is a message in the hold queue, it will display a exclamation point to the right of the message ID.

If a message is deferred, there will not be symbol / mark to the right of the message ID.

postqueue -p

-Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient-------  
5866DAC07F3 362 Sat Oct 12 15:53:56 [email protected]  
(connect to mail.tullyr.com[208.70.75.100]:25: Connection refused)  
<[email protected]>

Deleting Messages in the Postfix Queue

To delete messages from the Postfix queue, you can use the postsuper command. The postsuper tool can be used to delete a single message, or all messages in the queue.

To delete a single message from the queue, provide the -d switch followed by the message ID.

postsuper -d 5866DAC07F3

When you want to delete all messages in the queue, you provide postsuper with the word ALL in all capitals instead of the message ID.

postsuper -d ALL

NOTE – Be careful when using the postsuper command with the -d ALL switch. This command will delete all messages in the queue immediately without prompting you for verification.

Holding Messages in the Postfix Queue

The Postfix hold queue provides a place for messages to be held indefinitely. If you move a message into the hold queue, it will not be delivered until you specifically remove it or move it back into the normal queue processing.

To place a message in the hold queue, you use the tool postsuper with the -h switch followed by message ID.

postsuper -h 5866DAC07F3

When you need to move a messae back into the normal queue for processing, you use the postsuper command with the -H switch followed by the message ID.

postsuper -H 5866DAC07F3

Re-queue Messages in the Postfix Queue

If you have messages that are incorrect based on a misconfigured Postfix installation, you may need to re-queue the messages via the postsuper command. Some example of bad messages could be problems such as incorrect transport typeincorrect rewriting of an address, or an incorrect next hop.

After fixing the Postfix configuration, you can re-queue a single message or all messages. To requeue a message, you will use the postsuper command with the -r switch. When this command is run, it will update the incorrect information based on the new configuration.

To re-queue a single message you pass the message ID as in the example below.

postsuper -r 5866DAC07F3

If you need to re-queue all messages, you can pass the capital word ALL.

postsuper -r ALL

Displaying the Contents of Messages in the Postfix Queue

If you need to view the contents of a message in the queue, Postfix provides the postcat tool for this. The postcat tool will display the contents of a file when provided with the -q switch followed by the message ID.

postcat -q 5866DAC07F3

Flushing Messages in the Postfix Queue

If you have messages in the queue that you would like to flush, you can use the postqueue command with the -f switch. Flushing the queue will cause Postfix to attempt to deliver all messages in the queue immediately.

postqueue -f

There are times when this is needed. However, it’s usually not a good idea to flush all of the messages in the queue. If you do this a lot, it can have an impact on the performance on your mail server. You should leave the queue management to the Postfix queue manager.

With Postfix, it’s possible to flush only those messages that are going to a specific domain. You can do this with the -s switch provided by postqueue. However, to do this the domain must be eligible for fast flush.

For a domain to be eligible for fast flush, it must be listed in the fast_flush_domains parameter. In Postfix, the default value for the fast_flush_domains includes all of the hosts that are listed in relay_domains.

To add the site to the fast_flush_domains you can append it to the line fast_flush_domains as shown below:

fast_flush_domains = $relay_domains tullyrankin.com

Now if you want to flush mail that is destined for the domain you added to the fast_flush_domains, you can use the postqueue command with the -s option as shown below:

postqueue -s tullyrankin.com

Upload your images at scale

For the best performance, you should always upload your images at scale if possible. For example, if you have an image that you want to display at 200 px wide, don’t upload an image that is 400 px wide and then scale it with HTML. A better way to accomplish this is to use the srcset attribute in the <img> tag which allows you to define possible resolutions that the browser can choose from. Here an example:

<img srcset="/img/keycdn-300.jpg 300w,
             /img/keycdn-600.jpg 600w,
             /img/keycdn-1200.jpg 1200w"
     src="/img/keycdn-600.jpg" alt="KeyCDN">

Most modern web browsers support srcset, except IE and opera mini.