493

On an Amazon S3 Linux instance, I have two scripts called start_my_app and stop_my_app which start and stop forever (which in turn runs my Node.js application). I use these scripts to manually start and stop my Node.js application. So far so good.

My problem: I also want to set it up such that start_my_app is run whenever the system boots up. I know that I need to add a file inside init.d and I know how to symlink it to the proper directory within rc.d, but I can't figure out what actually needs to go inside the file that I place in init.d. I'm thinking it should be just one line, like, start_my_app, but that hasn't been working for me.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
meetamit
  • 24,727
  • 9
  • 57
  • 68
  • 5
    I'm no experte in this kind of stuff, but I think the `init.d` solution ([here](http://stackoverflow.com/a/12973826/131120)) should be preferred to the `rc.local` solution because the latter one is the old tooling which is only still usable because the new tooling is backward compatible. – erikbstack Nov 24 '13 at 13:57
  • pm2 start my_app; pm2 startup; pm2 save https://github.com/Unitech/pm2 – Unitech Aug 23 '17 at 15:36
  • In Raspbian there is a .config/lxsession/LXDE-pi/autostart which worked better for me - is there an equivalent in other operating systems? The reason it worked better for me was that not everything (in my case apache) is initialized when rc.local exectutes, whereas autostart is the start of the user session, so pretty much everything should initialized by then. – Chiwda Jan 20 '22 at 03:49

23 Answers23

528

First create your startup script @ /home/user/startup.sh, and make it executable

chmod +x /home/user/startup.sh

Then set a crontab for it:

$ crontab -e
@reboot  /home/user/startup.sh

Now your your startup.sh script will run at every start.

Black
  • 18,150
  • 39
  • 158
  • 271
Hemant kumar
  • 5,320
  • 1
  • 10
  • 4
  • 9
    This is the only solution that worked for me hassle free! thank you – whoopididoo Nov 09 '16 at 15:29
  • 45
    This is the best solution, `@reboot sh $HOME/test.sh` in the crontab is even cleaner – user3667089 Dec 29 '16 at 19:01
  • 8
    @user3667089 actually, it's not working. I open the terminal, enter "crontab -e", a window appears, where I write in "@reboot sh /home/user/test.sh" but it doesn't run at startup. Where am i doing it wrong? – MycrofD Jul 18 '17 at 10:03
  • 1
    @user3667089 the usual default lines '# Edit this file to ...' and then the line I wrote '@reboot sh /home/.../.sh' . I also tried '@reboot /home/.../.sh' without the initial "sh" but no results. – MycrofD Jul 18 '17 at 16:08
  • 5
    @MycrofD your `crontab -l` should show `@reboot sh $HOME/test.sh` to confirm that it is actually been set. – user3667089 Jul 23 '17 at 16:46
  • For me, `crontab -l` shows the same, but still I dont see the script getting called after reboot of the machine. `# uname -a Linux accton-xp70a0-26-a1 3.11.10-301.fc20.x86_64 #1 SMP Thu Dec 5 14:01:17 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux` –  Aug 10 '17 at 07:49
  • If it does not get called, you maybe need to put it under sudoers crontab with `sudo crontab -e` – Maksim Luzik Nov 27 '17 at 13:24
  • Note: if you run `ps` you won't see the script running, but if you run `ps -ef` you will see the script. – Michael Innes Apr 09 '18 at 21:38
  • I have used this method, but I had to remember to do also chmod +x on sh file – Čikić Nenad Jun 06 '18 at 11:02
  • 9
    In ubuntu you have to: `@reboot root sh script.sh` – Jurass Jun 04 '20 at 13:17
  • Using this I get a mail (In var/mail/$user) saying "Must be connected to a terminal." – Contrean Dec 16 '20 at 09:02
  • One advantage to this solution is you can run it as non root, putting it in the crontab of the corresponding user. – Nikolay Shindarov Apr 06 '21 at 11:29
  • 3
    It does not work for me at all – Álvaro Apr 16 '22 at 03:08
  • test the script executable status /home/user1/startup.sh – junnyea Sep 01 '22 at 08:03
  • @Jurass I believe the issue is that if you edit `/etc/crontab`, you must specify the user. But whether you are root or not, you don't specify the user when using `crontab -e`. [More details](https://askubuntu.com/questions/335615/does-ubuntu-support-reboot-in-crontab) – Josiah Yoder Feb 17 '23 at 20:22
347

The file you put in /etc/init.d/ have to be set to executable with:

chmod +x /etc/init.d/start_my_app

As pointed out by @meetamit, if it still does not run you might have to create a symbolic link to the file in /etc/rc.d/

ln -s /etc/init.d/start_my_app /etc/rc.d/

Please note that on the latest versions of Debian, this will not work as your script will have to be LSB compliant (provide at least the following actions: start, stop, restart, force-reload, and status): https://wiki.debian.org/LSBInitScripts

As a note, you should always use the absolute path to files in your scripts instead of the relative one, it may solve unexpected issues:

/var/myscripts/start_my_app

Finally, make sure that you included the shebang on top of the file:

#!/bin/sh
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Jonathan Muller
  • 7,348
  • 2
  • 23
  • 31
  • 10
    i did this and it didn't run. will it run automatically just because it is in /etc/init.d or do i need to do something on top to schedule it to run when the system starts? – amphibient May 08 '14 at 19:33
  • 6
    @amphibient Not quite enough... You also need to create a symlink to this file (using `ln` command) to a directory within `rc.d` – meetamit Jun 17 '14 at 20:44
  • 2
    it depend on distributive but, `rc-update add start_my_app` should be enough to make it run on boot with param "start" and shutdown with param "stop" – Sergei Krivonos Sep 27 '14 at 21:32
  • 30
    there is no rc.d directory in my root's etc folder.. this has me dumbfounded isn't this a crucial directory Linux needs to start up? It's just missing an my OS seems to run fine. Do I have to create it? I see a bunch of similarly named files like "rc1.d" all the way to "rc5.d" – OKGimmeMoney Feb 13 '15 at 21:12
  • 1
    I have the same issue as @OKGimmeMoney – ifconfig May 24 '16 at 20:52
  • 1
    @sudoprogrammer.sh did you do ln -s /etc/init.d/start_my_app /etc/rc.d/? you can do it without the / at the end ln -s /etc/init.d/start_my_app /etc/rc.d and it got rid of that error. – Jihoon Baek Aug 05 '16 at 18:46
  • 1
    If you use the `LSB header` use `update-rc` (ubuntu) and `chkconfig -add` (centos) to create the symlinks for you. – zaphod Sep 01 '16 at 18:46
  • 6
    I haven't any `/etc/rc.d` folder, but I have `/etc/rcX.d` folders (I.e. _/etc/rc0.d_, _/etc/rc1.d_, _/etc/rcS.d_), also there's a file **/etc/rc.local**. I think that you should create symlinks in custom folder like `/etc/rc9.d` or in one of existing ... ( Ubuntu Server 14.04 ) – Artfaith Feb 10 '17 at 20:42
  • 3
    This question helped me with this: http://unix.stackexchange.com/questions/28679/whats-the-connection-between-etc-init-d-and-etc-rcx-d-directories-in-linu – seth10 Mar 23 '17 at 13:45
  • 1
    There is no default path defined at this level. to avoid mystery failures, you should make all references using the full path – fcm Jul 25 '17 at 22:20
  • 2
    I don't understand the statement 'In the file you put in'....could someone clarify? – Scorb Jan 16 '18 at 01:27
  • 1
    It worked for me. The fix is to use the _full path_ always. – JeanCarlos Chavarria May 11 '18 at 20:54
  • Not the best solution. If the script take a long time to run, the system will wait until the script finish, and so, to release the shell control. – Potter Jun 23 '22 at 19:28
129

A simple approach is to add a line in /etc/rc.local :

/PATH/TO/MY_APP &

or if you want to run the command as a special user :

su - USER_FOOBAR -c /PATH/TO/MY_APP &

(the trailing ampersand backgrounds the process and allows the rc.local to continue executing)

If you want a full init script, debian distro have a template file, so :

cp /etc/init.d/skeleton /etc/init.d/your_app

and adapt it a bit.

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • 2
    Thanks! This approach turned out to work best given the simple requirements. I'm pretty sure I DID need to specify the user, otherwise when needing to manually stop the app (by running `stop_my_app`) I'd have to do so with `sudo`, no? Also, I'm wondering what exactly is the function of the trailing ampersand(?). – meetamit Oct 19 '12 at 14:42
  • 3
    The user depends of your app. But if not absolutely needed to run as root, avoid it. `&` run the process in background – Gilles Quénot Oct 19 '12 at 14:51
  • 2
    sputnick, sorry, but I gotta mark Koren's as the accepted answer, mainly because of what @erikb85 pointed out, but also because my original question asked for the `init.d` way of doing things (your answer was just a simpler workaround for me at the time). This post gets a lot of views and votes, so it's important to keep accurate. – meetamit Nov 25 '13 at 16:56
  • 4
    It dosnt seem to be mentioned that the trailing ampersand backgrounds the process and allows the rc.local to continue executing. – mchicago Feb 14 '14 at 16:19
  • Thanks for this! Spend last few hours hitting my head against the wall while I was trying to make a service, but nothing worked. Tried this, works like a charm! – Marko Gresak Jun 01 '15 at 03:57
  • this doesn't work if you have not rc.local such as in kali – rockower Apr 18 '18 at 21:54
  • `&` users' background processes don't work if OS doesn't have an option `KillUserProcesses=no` in `/etc/systemd/logind.conf` – Rapekas Feb 17 '23 at 11:07
39

This is the way I do it on Red Hat Linux systems.

Put your script in /etc/init.d, owned by root and executable. At the top of the script, you can give a directive for chkconfig. Example, the following script is used to start a Java application as user oracle.

The name of the script is /etc/init.d/apex

#!/bin/bash
# chkconfig: 345 99 10
# Description: auto start apex listener
#
case "$1" in
 'start')
   su - oracle -c "cd /opt/apex ; java -jar apex.war > logs/apex.log 2>logs/apex_error.log &";;
 'stop')
   echo "put something to shutdown or kill the process here";;
esac

This says that the script must run at levels 3, 4, and 5, and the priority for start/stop is 99 and 10.

Then, as user root you can use chkconfig to enable or disable the script at startup:

chkconfig --list apex
chkconfig --add apex

And you can use service start/stop apex.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Saule
  • 579
  • 5
  • 6
  • In the meantime I have experimented with a package called supervisord (http://supervisord.org/) which is available in the epel repository. It can be used to start programs and to monitor them, restarting them on failure. – Saule Nov 19 '14 at 15:30
  • Instead of typing: "chkconfig --add service_name" after putting script to /etc/init.d/ folder you can type: "chkconfig service_name on" – Dragan Radevic Sep 14 '16 at 13:44
36

Enter cron using sudo:

sudo crontab -e

Add a command to run upon start up, in this case a script:

@reboot sh /home/user/test.sh

Save:

Press ESC then :x to save and exit, or hit ESC then ZZ (that's shift+zz)

Test Test Test:

  1. Run your test script without cron to make sure it actually works.

  2. Make sure you saved your command in cron, use sudo crontab -e

  3. Reboot the server to confirm it all works sudo @reboot

Omar Ali
  • 8,467
  • 4
  • 33
  • 58
user3140639
  • 509
  • 4
  • 3
18

Just have a line added to your crontab..

Make sure the file is executable:

chmod +x /path_to_you_file/your_file

To edit crontab file:

crontab -e

Line you have to add:

@reboot  /path_to_you_file/your_file

That simple!

Patrick Q
  • 6,373
  • 2
  • 25
  • 34
  • 1
    This doesn't work for me, anything I am missing? `# uname -a Linux accton-xp70a0-26-a1 3.11.10-301.fc20.x86_64 #1 SMP Thu Dec 5 14:01:17 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux` –  Aug 10 '17 at 07:46
  • This worked for me on CentOs 7. For those with issues, I did need to create a shell script, make it executable (chmod +x file_name), and call the shell script from the cron which in turn calls node path_to_file/index.js – SeanOlson Nov 27 '18 at 23:52
14

Another option is to have an @reboot command in your crontab.

Not every version of cron supports this, but if your instance is based on the Amazon Linux AMI then it will work.

chris
  • 36,094
  • 53
  • 157
  • 237
11

Edit the rc.local file using nano or gedit editor and add your scripts in it. File path could be /etc/rc.local or /etc/rc.d/rc.local.

sudo nano /etc/rc.local

This is the edit:

#!/bin/sh
/path-to-your-script/your-scipt-name.sh

once done press ctrl+o to update, pressEnter then ctrl+x.

Make the file executable.

sudo chmod 755 /etc/rc.local

Then initiate the rc-local service to run script during boot.

sudo systemctl start rc-local
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Dohd
  • 359
  • 3
  • 7
7

You can do it :

chmod +x PATH_TO_YOUR_SCRIPT/start_my_app 

then use this command

update-rc.d start_my_app defaults 100

Please see this page on Cyberciti.

sobolevn
  • 16,714
  • 6
  • 62
  • 60
IR PRO
  • 75
  • 1
  • 6
5

Many answers on starting something at boot, but often you want to start it just a little later, because your script depends on e.g. networking. Use at to just add this delay, e.g.:

at now + 1 min -f /path/yourscript

You may add this in /etc/rc.local, but also in cron like:

# crontab -e
@reboot at now + 1 min -f /path/yourscript

Isn't it fun to combine cron and at? Info is in the man page man at.

As for the comments that @reboot may not be widely supported, just try it. I found out that /etc/rc.local has become obsolete on distros that support systemd, such as ubuntu and raspbian.

Roland
  • 4,619
  • 7
  • 49
  • 81
3

The absolute easiest method if all you want to run is a simple script, (or anything) is if you have a gui to use system > preferences then startup apps.

just browse to the script you want and there you go. (make script executable)

  • 3
    This doesn't actually run on startup, but on login, which is a pretty big difference. It also depends on a certain setup since you won't have "System > Preferences" on every system (especially not servers). – jazzpi Oct 10 '15 at 11:40
  • the search term 'linux execute at startup' led me to this answer, for which I was looking. Even though it does not answer the question by OP, this might help linux (ubuntu) noobs like me, so it deserves an upvote. I don't like it either, but that's pragmatism. – thymaro Jun 02 '20 at 21:23
3

This simple solution worked for me on an Amazon Linux instance running CentOS. Edit your /etc/rc.d/rc.local file and put the command there. It is mentioned in this file that it will be executed after all other init scripts. So be careful in that regards. This is how the file looks for me currently.enter image description here. Last line is the name of my script.

shshnk
  • 1,621
  • 14
  • 26
3

Create your own /init executable

This is not what you want, but it is fun!

Just pick an arbitrary executable file, even a shell script, and boot the kernel with the command line parameter:

init=/path/to/myinit

Towards the end of boot, the Linux kernel runs the first userspace executable at the given path.

Several projects provide popular init executables used by major distros, e.g. systemd, and in most distros init will fork a bunch of processes used in normal system operation.

But we can hijack /init it to run our own minimal scripts to better understand our system.

Here is a minimal reproducible setup: https://github.com/cirosantilli/linux-kernel-module-cheat/tree/f96d4d55c9caa7c0862991025e1291c48c33e3d9/README.md#custom-init

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
3

I refered to this blog, always sound a good choice

https://blog.xyzio.com/2016/06/14/setting-up-a-golang-website-to-autorun-on-ubuntu-using-systemd/

vim /lib/systemd/system/gosite.service

[Unit]
Description=A simple go website
ConditionPathExists=/home/user/bin/gosite
 
[Service]
Restart=always
RestartSec=3
ExecStart=/home/user/bin/gosite
 
[Install]
WantedBy=multi-user.target
systemctl enable gosite.service
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
王子1986
  • 3,019
  • 4
  • 31
  • 43
3

multi ways to finish it:

  1. crontab
  2. rc.local
  3. init.d
  4. systemd
Ridox
  • 1,073
  • 13
  • 18
  • 2
    Please note that linked content is not considered part of the answer here. So your post is seen as "multi ways to do it; unexplained keywords". That is unlikely to be perceived as a helpful answer. Please take the [tour] and read [answer]. – Yunnosch Sep 17 '21 at 08:46
1

For Debian 9 see https://askubuntu.com/questions/228304/how-do-i-run-a-script-at-start-up. It is helped me. Short version for Debian 9: add commands (as root) to /etc/rc.local

/path_to_file/filename.sh ||  exit 1   # Added by me
exit 0

Probably, /path_to_file/filename.sh should be executable (I think so).

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Mikhail Ionkin
  • 568
  • 4
  • 20
1

In Lubuntu I had to deal with the opposite situation. Skype start running after booting and I found in ~/.config/autostart/ the file skypeforlinux.desktop. The content of the file is as follows:

[Desktop Entry]
Name=Skype for Linux
Comment=Skype Internet Telephony
Exec=/usr/bin/skypeforlinux
Icon=skypeforlinux
Terminal=false
Type=Application
StartupNotify=false
X-GNOME-Autostart-enabled=true

Deleting this file helped me.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
aerijman
  • 2,522
  • 1
  • 22
  • 32
1

Here is a simpler method!

First: write a shell script and save it a .sh here is an example

#!/bin/bash
Icoff='/home/akbar/keyboardONOFF/icon/Dt6hQ.png'
id=13
fconfig=".keyboard"
echo "disabled" > $fconfig
xinput float $id
notify-send -i $Icoff "Internal Keyboard disabled";

this script will disable the internal keyboard at startup.

Second: Open the application " Startup Application Preferences"

enter image description here

enter image description here

Third: click Add. fourth: in the NAME section give a name. fifth: In the command section browse to your .sh . sixth: edit your command section to:

bash <space> path/to/file/<filename>.sh <space> --start

seventh: click Add. Thats it! Finished!

Now confirm by rebooting your pc.

cheers!

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
akbar ali
  • 25
  • 5
1

Solutions

Without further ado, let’s give execute permission to your script:

$ chmod +x YOUR_SCRIPT.sh

Now let’s see how to schedule its execution.

1. Using cron Let’s begin with the easiest solution, which involves using cron. In order to do this, we need to edit our crontab file:

$ crontab -e

Here we’ll add a line using the @reboot expression, which will execute our code once at startup:

@reboot sh /home/ec2-user/YOUR_SCRIPT.sh

This solution is quick and clean, since we don’t have to deal with additional configuration, but not every version of cron supports @reboot.

2. Using rc.local Now let’s consider another solution that takes advantage of the /etc/rc.d/rc.local file. Since this file already runs at startup, we can append a line that invokes our script:

sh /home/ec2-user/YOUR_SCRIPT.sh

In order for this to work, we need to ensure that the rc.local file itself is executable:

$ chmod +x /etc/rc.d/rc.local

3. Using init.d Similar to the previous solution, the /etc/init.d folder contains lifecycle executables of the services managed by the system. We can also add our own by creating an LSB-compliant wrapper that starts our service:

#! /bin/sh
# chkconfig: 345 99 10
case "$1" in
  start)
    # Executes our script
    sudo sh /home/ec2-user/YOUR_SCRIPT.sh
    ;;
  *)
    ;;
esac
exit 0

This wrapper will launch our code when it’s invoked with the start argument. However, we must include a line with the chkconfig configuration, which contains the service runlevel and the start/stop priority.

After placing the wrapper in the init.d folder, we need to register our service for startup execution:

$ chkconfig --add service_wrapper.sh

Since the chkconfig command isn’t available on Debian systems, update-rc.d can be used as an alternative there:

$ update-rc.d service_wrapper.sh defaults

Hope it helps, if yes, please upvote.

Bipul Jaishwal
  • 273
  • 2
  • 15
0
  • Add your script to /etc/init.d/ directory
  • Update your rc run-levels: $ update-rc.d myScript.sh defaults NN where NN is the order in which it should be executed. 99 for example will mean it would be run after 98 and before 100.
Kibrom Gebre
  • 119
  • 1
  • 10
0

Painless, easiest and the most universal method is simply executing it with ~.bash_profile or ~.profile (if you don't have bash_profile file).

Just add the execution command at the bottom of that file and it will be executed when system started.

I have this one at the bottom an example; ~\Desktop\sound_fixer.sh

Juko
  • 39
  • 2
  • 4
    That's inaccurate. `~/.bash_profile` executes when the user logs in -- **not** when the system boots up. In the original question, the intent is to run a Node.js app server upon startup of the machine. Your solution would require a human user to first log into the machine before the Node.js server runs. And, if some kind of issue causes a server reboot overnight, the app will never come back to life until the human logs back in. – meetamit May 13 '19 at 16:46
0

Working with Python 3 microservices or shell; using Ubuntu Server 18.04 (Bionic Beaver) or Ubuntu 19.10 (Eoan Ermine) or Ubuntu 18.10 (Cosmic Cuttlefish) I always do like these steps, and it worked always too:

  1. Creating a microservice called p example "brain_microservice1.service" in my case:

    $ nano /lib/systemd/system/brain_microservice1.service
    
  2. Inside this new service that you are in:

    [Unit]
    Description=brain_microservice_1
    After=multi-user.target
    
    [Service]
    Type=simple
    ExecStart=/usr/bin/python3.7 /root/scriptsPython/RUN_SERVICES/microservices    /microservice_1.py -k start -DFOREGROUND
    ExecStop=/usr/bin/python3.7 /root/scriptsPython/RUN_SERVICES/microservices/microservice_1.py -k graceful-stop
    ExecReload=/usr/bin/python3.7 /root/scriptsPython/RUN_SERVICES/microservices/microservice_1.py -k graceful
    PrivateTmp=true
    LimitNOFILE=infinity
    KillMode=mixed
    Restart=on-failure
    RestartSec=5s
    
    [Install]
    WantedBy=multi-user.target
    
  3. Give the permissions:

    $ chmod -X /lib/systemd/system/brain_microservice*
    $ chmod -R 775 /lib/systemd/system/brain_microservice*
    
  4. Give the execution permission then:

    $ systemctl daemon-reload
    
  5. Enable then, this will make then always start on startup

    $ systemctl enable brain_microservice1.service
    
  6. Then you can test it;

    $ sudo reboot now
    
  7. Finish = SUCCESS!!

This can be done with the same body script to run shell, react ... database startup script ... any kind os code ... hope this help you...

...

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
-6

For some people, this will work:

You could simply add the following command into SystemPreferencesStartup Applications:

bash /full/path/to/your/script.sh
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SagarSave
  • 31
  • 2
  • I don't see this in the system preferences menu. But I do see it when I search in the application launcher. – OKGimmeMoney Feb 13 '15 at 21:21
  • This doesn't actually run on startup, but on login, which is a pretty big difference. It also depends on a certain setup since you won't have "System > Preferences" on every system (especially not servers). – jazzpi Oct 10 '15 at 11:41
  • 4
    This answer seems more for Ubuntu/Linux desktop, but the user is actually requesting help for an AWS EC2 Linux instance, which as far as I know, have no GUI. – Vini.g.fer Apr 19 '17 at 13:12