The position of samurai was hereditary, you had to be born into it. It was very rare for someone born outside the samurai class to become one, although it could happen. A famous case was Toyotomi Hideyoshi, who started off as the son of a peasant, became a soldier, earned favor with the daimyo Oda Nobunaga and was promoted to samurai, eventually rising to the rank of imperial regent.
As for knights, in theory, anyone could become a knight if they were made one by another knight, a lord or the king. In practice, knights were mostly the son of nobility as only they could afford the horse and armor, and their training started from an early age (starting off as a page, then serving under another knight as a squire, then eventually becoming a knight in a ceremony around age 18).