From high school chemistry, almost 30 years ago, the basic explanation that we were given (not overly scientific) is as follows.
Each atom "wants" to have a full outer electron shell. For noble gasses, this is the default because they hit the right number and are full, so they don't react. For everything else, the amount they are short or over dictates how they react.
Covalent bonds:
For each electron short, the atom wants to interact with other atoms that can "share" their electrons so that the outer shell "feels full". Oxygen is -2 electrons so it can connect with another oxygen and both share 2 electrons so that they "feel full". Carbon is -4 electrons so finds some way of connecting with things to make up that deficit, which works in $\ce{CO2}$ by sharing 2 electrons each with the oxygen atoms that want to share 2 each.
Ionic bonds:
Everything in column 1 of the periodic table is +1 in its outer electron shell, and thus highly unstable because they really want to get rid of that extra electron. This makes hydrogen, sodium, and the like to behave (when isolated) as an explosive. This works well for elements in the next-to-last column of the periodic table that are of the -1 variety in their outer electron shell. Sodium will freely give up its unwanted electron to form an ionic bond with chlorine, turning an explosive and a poison gas into harmless table salt.