How to run a script as a service in UBUNTU - linux

I have a script which normally i run using ./myscript.sh(contain java run command) on linux. Now i want to make it as a service so it run automatically after machine restart and if i want to stop and start again simply find the process and kill and start it again from command line.
What i find with quick google search is to place the script in /etc/init.d directory but confusing with one thing that command inside this script using other certificate files which i normally place on same level where this script is place. Do i need to move all others file along with this script under /etc/init.d or is there any better way that i simply mention the path of this script in some file?

You need to write systemd service file.
Simplest script looks like this:
[Unit]
Description=Virtual Distributed Ethernet
[Service]
ExecStart=/usr/bin/YOUR_SCRIPT
[Install]
WantedBy=multi-user.target
Also you need: systemctl daemon-reload after creating new service.

Related

How to restart a running python script if the Ubuntu 16.04 server crashes automatically?

I have a simple script
#!/usr/bin/env python
# coding: utf-8
i=0
while (True):
print(i)
i=i+1
I want this script to run in background
If the server crashes, I want it to automatically restart an pick where the program left of
How do I do that
You have tu run your script as a service:
The file must have .service extension under /lib/systemd/system/ directory.
Now Your system service has been added to your service. Let’s reload the systemctl daemon to read new file. You need to reload this deamon each time after making any changes in in .service file.
sudo systemctl daemon-reload
Now enable the service to start on system boot, also start the service using the following commands.
sudo systemctl enable dummy.service
sudo systemctl start dummy.service
I personally use supervisord to handle processes. To make your script start where it left off you need some kind of persistence, like a file or a database where you can put the last state of your script and read at the restart.

How to run a go app continously on an Ubuntu server

Couldn't seem to find a direct answer around here.
I'm not sure if I should run ./myBinary as a Cron process or if I should run "go run myapp.go"
What's an effective way to make sure that it is always running?
Sorry I'm used to Apache and Nginx.
Also what are best practices for deploying a Go app? I want everything (preferably) all served on the same server. Just like how my development environment is like.
I read something else that used S3, but, I really don't want to use S3.
Use the capabilities your init process provides. You're likely running system with either Systemd or Upstart. They've both got really easy descriptions of services and can ensure your app runs with the right privileges, is restarted when anything goes down, and that the output is are handled correctly.
For quick Upstart description look here, your service description is likely to be just:
start on runlevel [2345]
stop on runlevel [!2345]
setuid the_username_your_app_runs_as
exec /path/to/your/app --options
For quick Systemd description look here, your service is likely to be just:
[Unit]
Description=Your service
[Service]
User=the_username_your_app_runs_as
ExecStart=/path/to/your/app --options
[Install]
WantedBy=multi-user.target
You can put it in an inifiny loop, such as:
#! /bin/sh
while true; do
go run myapp.go
sleep 2 # Just in case
done
Hence, once the app dies due some reason, it will be run again.
You can put it in a script and run it in background using:
$ nohup ./my-script.sh >/dev/null 2>&1 &
You may want to go for virtual terminal utility like screen here. Example:
screen -S myapp # create screen with name myapp
cd ... # to your app directory
go run myapp.go # or go install and then ./myappfrom go bin dir
Ctrl-a+d # to go out of screen
If you want to return to the screen:
screen -r myapp
EDIT: this solution will persist the process when you go out of terminal, but won't restart it when it'll crash.

systemd --user for normal graphical applications

I'm trying to set up systemd to start some programs when I log in. I'm doing this by putting files in e.g. ~/.config/systemd/user/some.service. This has worked for my emacs server service, which looks like this:
[Unit]
Description=Emacs: the extensible, self-documenting text editor
[Service]
Type=forking
ExecStart=/usr/bin/emacs --daemon
ExecStop=/usr/bin/emacsclient --eval "(kill-emacs)"
Environment=SSH_AUTH_SOCK=%t/keyring/ssh
Restart=always
[Install]
WantedBy=default.target
This starts a background process and allows me to connect to the emacs service with emacsclient
What's not working is my terminator service:
[Unit]
Description=The only terminal emulator that seems to be somewhat decent
After=multi-user.target
[Service]
ExecStart=/usr/bin/terminator
Restart=always
Environment=DISPLAY=:0
[Install]
WantedBy=default.target
With this code in ~/.config/systemd/user/terminator.service I can start terminator on the command-line with systemctl --user start terminator, but I can't get terminator to start automatically on (graphical) login. I've tried messing around with the WantedBy and After lines, switching between to graphical.target, default.target and multi-user.target, but it's really just guess work and hasn't helped.
Any ideas?
your terminator service file looks okay to me.
check below things
1. just check "default.target" file, is this below line present in that file
After=multi-user.target
2. if you write "WantedBy=default.target" then you need to create a soft link of terminator.service file inside "default.target.wants/" directory.
if this above two are correct, it should get start.
If still doesn't work, please remove "After=multi-user.target" this line, and change Wantedby as "WantedBy=graphical.target".
let me know the status of service after login
systemctl status terminator.service
Systemd is not the right tool for this task because it doesn't know when you have finished logging in in a desktop environment and it's possible to launch terminator. Instead, you could put a symlink to terminator's desktop file in your ~/.config/autostart :
ln -s /usr/share/applications/terminator.desktop ~/.config/autostart/
Most desktop interfaces (Gnome, KDE, Unity) will launch it when they start.

How do I get my Golang web server to run in the background?

I have recently completed the Wiki web development tutorial (http://golang.org/doc/articles/wiki/). I had tons of fun and I would like to experiment more with the net/http package.
However, I noticed that when I run the wiki from a console, the wiki takes over the console. If I close the console terminal or stop the process with CTRL+Z then the server stops.
How can I get the server to run in the background? I think the term for that is running in a daemon.
I'm running this on Ubuntu 12.04. Thanks for any help.
Simple / Usable things first
If you want a start script without much effort (i.e. dealing with the process, just having it managed by the system), you could create a systemd service. See Greg's answer for a detailled description on how to do that.
Afterwards you can start the service with
systemctl start myserver
Previously I would have recommended trying xinetd or something similar for finer granuarlity regarding resource and permission management but systemd already covers that.
Using the shell
You could start your process like this:
nohup ./myexecutable &
The & tells the shell to start the command in the background, keeping it in the job list.
On some shells, the job is killed if the parent shell exits using the HANGUP signal.
To prevent this, you can launch your command using the nohup command, which discards the HANGUP signal.
However, this does not work, if the called process reconnects the HANGUP signal.
To be really sure, you need to remove the process from the shell's joblist.
For two well known shells this can be achieved as follows:
bash:
./myexecutable &
disown <pid>
zsh:
./myexecutable &!
Killing your background job
Normally, the shell prints the PID of the process, which then can be killed using the kill command, to stop the server. If your shell does not print the PID, you can get it using
echo $!
directly after execution. This prints the PID of the forked process.
You could use Supervisord to manage your process.
Ubuntu? Use upstart.
Create a file in /etc/init for your job, named your-service-name.conf
start on net-device-up
exec /path/to/file --option
You can use start your-service-name, as well as: stop, restart, status
This will configure your service using systemd, not a comprehensive tutorial but rather a quick jump-start of how this can be set up.
Content of your app.service file
[Unit]
Description=deploy-webhook service
After=network.target
[Service]
ExecStart=/usr/bin/go webhook.go
WorkingDirectory=/etc/deploy-webhook
User=app-svc
Group=app-svc
Restart=always
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=deploy-webhook-service
PrivateTmp=true
Environment=APP_PARAM_1=ParamA
Environment=APP_PARAM_2=ParamB
[Install]
WantedBy=multi-user.target
Starting the Service
sudo systemctl start deploy-webhook.service
Service Status
sudo systemctl status deploy-webhook.service
Logs
journalctl -u deploy-webhook -e
After you press ctrl+z (putting the current task to sleep) you can run the command bg in the terminal (stands for background) to let the latest task continue running in the background.
When you need to, run fg to get back to the task.
To get the same result, you can add to your command & at the end to start it in the background.
To add to Greg's answer:
To run the Go App as a service you need to create a new service unit file.
However, the App needs to know where Go is installed. The easiest way to lookup that location is by running this command:
which go
which gives you an output like this:
/usr/local/go/bin/go
With this piece of information, you can create the systemd service file. Create a file named providus-app.service in the /etc/systemd/system/ using the command below:
sudo touch /etc/systemd/system/providus-app.service
Next open the newly created file:
sudo nano /etc/systemd/system/providus-app.service
Paste the following configuration into your service file:
[Unit]
Description=Providus App Service
After=network.target
[Service]
Type=forking
User=deploy
Group=deploy
ExecStart=/usr/local/go/bin/go run main.go
WorkingDirectory=/home/deploy/providus-app
Restart=always
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=providus-app-service
PrivateTmp=true
[Install]
WantedBy=multi-user.target
When you are finished, save and close the file.
Next, reload the systemd daemon so that it knows about our service file:
sudo systemctl daemon-reload
Start the Providus App service by typing:
sudo systemctl restart providus-app
Double-check that it started without errors by typing:
sudo systemctl status providus-app
And then enable the Providus App service file so that Providus App automatically starts at boot, that is, it can start on its own whenever the server restarts:
sudo systemctl enable providus-app
This creates a multi-user.target symlink in /etc/systemd/system/multi-user.target.wants/providus-app.service for the /etc/systemd/system/providus-app.service file that you created.
To check logs:
sudo journalctl -u providus-app

python - daemonize bottlepy script

I'm using a Bootle Python Web Framework to develop webapps on Ubuntu.
Is there any effective way to daemonize script that starts default bottlepy webserver?
Thank you.
UPD: Now I'm using Supervisord for this purposes.
As reclosedev mentions, nohup ... & will work without fuss.
You can also use something like daemonize Which has more options than using nohup.
Personally I run the following while developing with autoreload switched on:
while true; do python app.py ; done
which restarts the server if I write something stupid. Other solutions will force you to restart your server for a syntax error.
Deployment happens behind apache or lighttpd.
On ubuntu I use following steps:
Remember to insert full path to templates into bottle.TEMPLATE_PATH
Make script executable (chmod +x <script_name>)
Make symlink to script w/o .py extension
Navigate to /etc/init.d and copy skeleton to <script_symlink_name>
Modify new init script
Change NAME to <script_symlink_name>
Change DAEMON to <path_to_script_symlink>
Change DAEMON_ARGS to ""
Change DESCRIPTION
Add "--background" switch to start-stop-daemon (line w/o "--test" switch) in do_start()
Make init script executabe
Test via "service <script name> start"
Set autostart: update-rc.d <script-name> defaults
You can use supervisord or monit to start/stop and restart the app.

Resources