The samurai were not mercenary warriors, roaming Japan and fighting for whatever warlord would pay them. They were bound to a specific lord, or daimyo, and also bound to their communities by duty and honor.
This code of honor is known as Bushido, and comes from the word bushi, which means "warrior." The Japanese word do means "the way." So Bushido means, "the way of the warrior." This code evolved from an earlier period, when samurai were archers and horsemen. The training and devotion needed to master these skills and bond with a horse led to kyuba no michi, "the way of the horse and bow."
Although Bushido is referred to as a code, it was not a formal set of rules that all samurai followed. In fact, Bushido changed greatly throughout Japanese history and even from one clan to the next. Bushido wasn't written down at all until the 17th century, after samurai had been in existence for centuries.
The first duty of a samurai was loyalty to his lord. Japan had a feudal system, in which a lord expected obedience from his vassals, who in turn received economic and military protection from the lord. If a lord couldn't count on absolute loyalty from his vassals, the entire system would have collapsed. This sense of loyalty and honor was often carried to extremes by the Japanese, who would fight to the death in a hopeless battle to protect their master's castle, or commit suicide if they felt they had disgraced their lord.
Samurai also had a duty of vengeance. Should the honor of his master be tarnished, or his master killed, a samurai was required to seek out and kill those responsible. One of the most famous samurai stories, "The 47 Ronin," or masterless samurai, is a tale of traditional samurai vengeance. During a period of peace, their lord was ordered to commit seppuku because of an altercation with another lord. Two years later, all 47 samurai invaded the lord's castle and killed him. They were arrested and forced to commit seppuku, not because they had fulfilled their duty of vengeance (this was expected), but because they had done it with a secret attack, which was considered dishonorable.