This is a prototypical case of evolution by natural selection. Any trait that prevents the organism from being eaten or destroyed will probably make that organism more likely to reproduce* than similar organisms that do not have that trait**. This results in self-preservation traits becoming more prevalent in the population and eventually ubiquitous.
* Or they reproduce more, or are able to provide for their offspring better, etc. Self-preservation behaviors that reduce reproductive success are not selected for and generally aren't common (unless they are a special case of some general trait that has a net reproductive benefit).
** Assuming that the trait is reproductively favorable after considering any trade-offs such as increased energy expenditure.