How do bonds work as an investment, and what are the key factors that influence their value?

If I understand correctly, when you buy a bond, you are essentially lending money to the government. In return, the government promises to pay you back the principal amount plus accumulated interest. While holding the bond, you earn interest annually. When you sell the bond, you would get your initial investment back along with the accumulated interest. It's similar to a CD in that you can't really lose the principal. Is that right? If so, what doesn’t make sense is: what happens when bond rates are negative?